6. Control structures
if [ condition ]; then action; else action; fi
for i in {1..n}; do action $i; done
for ((c=0;c<10;c++)); do echo $c; done
while read line; do action $line ; done < infile
case $var in 1|3|5) echo 1 ;; *) echo 0 ;; esac
Meanings
$?, $$, $#, $@, $1, $2, $3
7. Quoting
Double quotes (weak):
“ $this is going to be interpreted ”
Single quotes (strong):
‘ this is not going to be interpreted ‘
Backquotes ( or backticks ):
` /this/is/going/to/be/executed/with/its args `
Variables expansion:
“ ${ /the/result/may/be/quoted! } ”
9. Redirections
> and >> ( without descriptors STDOUT is assumed )
1 is STDOUT, 2 is STDERR
e.g.: command 1> stdout.txt 2> stderr.txt
2>&1 means “send STDERR to STDOUT”
1>&2 means “send STDOUT to STDERR”
>& and &> without descriptors redirect both 1 and 2
14. Sed in pills
sed ‘3d’ - delete the 3rd line of the stream
sed ‘/^$/d’ - delete blank lines
sed -n ‘/pattern/p/ - print all pattern-matching lines
(by default all lines are also echoed, -n to suppress)
sed ‘s/find/replace/g’ - substitute all matching with a
replacement
sed ‘s/quote/”&”/’ - use & to copy the matched
pattern
echo "ff66" | sed 's/([a-z]*)(.*)/21/' - use 1 2
etc to copy portions of the matched pattern
15. How to use sed
cat file | sed ‘s/search/replace/g’
sed -e ‘cmd’ -i .ext file ( In place editing. If .ext is
given, original files will be moved to file.ext )
sed ‘cmd’ <old_file >new_file
16. Exercise
What is this ?
find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
( hint: ; may be used as separators, like / or _ )
18. AWK
cat file | awk [opt] ‘pattern {action} [pattern {action}]’
input is parsed in records
foreach record
foreach pattern
if record match pattern -> action
default action : print $0
$0 is the entire record
$1 is the 1st field, $2 the 2nd, etc.