- deal with text file which is thought of as being made up of records and fields. we can write programing by awk to do anything we want.
- we can:execute UNIX command from within a script; process the output from UNIX commands; work with multiple input streams; define functions.
- we can combined with sed and shell scripting. compared: shell is very easy and quick to write, but lacks functionality. sed, awk, and shell are designed to be integrated.
invoke:
- awk [options] 'script' var=value file(s)
- awk [options] -f scriptfile var=value file(s) : we can have more than one -f scriptfile.
- a literal: awk -f scriptFile count=5
- a shell variable: awk -f scriptFile count=$count
- A command substitution: awk -f scriptFile count=`who wc-l`
set filed seperator:
- using -F
- one line can be sperated into different filed and can be refered by variables $1, $2 etc. $0 means the whole record.
awk script consist of patterns and procedure:
- a pattern can be : /regular expression/, eg /^...:/ or relational expression, eg $1=="gdm". ~ means match, !~ means don't match, eg awk -F: '$1 ~ /.dm.*/ {print $0}' /etc/passwd. BEGIN specifies procedure to take place before the first input line is processed, END as well, eg awk ‘BEGIN {print “Version 1.0”}’ dataFile. pattern missing, the procedure applies all lines
- procedure is arround by {} and seperated by newlines or semi-colons. can be: commands, functions and veriable assignment. procedure missing, printed all lines matched by pattern.
commands used with procedures: 5 types
- Assignments of variables or arrays
- Commands that print
- Built-in functions
- Control-flow commands
- User-defined functions (in nawk only)
awk Built-in Variables:
- FILENAME - current filename
- FS - Field separator
- NF - Number of fields in current record
- NR - Number of current record
- RS - Record separator
- $0 - Entire input record
- $n - nth field in current record
awk operators: $_++_ --_ +_-_!_*_/_%_<_<=_>=_>_!=_==_~_!~_in_$$__?:_=_+=_-+_*=_/=_%=
two ways to usingarrays in awk:
- in an assignment statement: myArray[i]++
- split() function : n=splict(input,words," ") : splict this input by " "(whitespace) into words.
functions in awk: works in the same way as java: calling a function, no sapce between function name and left bracket.
No comments:
Post a Comment