Awk: Difference between revisions
Jump to navigation
Jump to search
Created page with ";awk '{ for(i = 1; i <= NF; i++) { print $i; } }' :Itterate over all fields" |
No edit summary |
||
| Line 1: | Line 1: | ||
;awk '{ for(i = 1; i <= NF; i++) { print $i; } }' | ;awk '{ for(i = 1; i <= NF; i++) { print $i; } }' | ||
:Itterate over all fields | :Itterate over all fields | ||
==String manipulation== | |||
;substr(<string>,<start>,<num>) | |||
:From <sting> return <num> characters, starting from <start> | |||
;n=split(var,ARR,<fs>) | |||
:Split var in array ARR, n holds the number of elements in ARR, <fs> is the field separator, if not given the variable FS is used as field separator (default white space). :Default action of awk for read line is NF=split(var,ARR," ") | |||
<syntaxhighlight lang=awk> | |||
NR++ | |||
$0=var | |||
for ( i=1 ; i<=NF ; i++ ) { | |||
$i=ARR[i] | |||
} | |||
</syntaxhighlight> | |||
;gsub(<regexp>,<string>,<variable>) | |||
:Replace <regexp> with <string> in <variable>. Return number of replacements. | |||
:<variable> is modified. | |||
==Calculations== | |||
Print average of field 4 for all records in <file> containing 'GW' | |||
<syntaxhighlight lang=awk> | |||
awk 'BEGIN {} | |||
/GW/ {GW+=$4} | |||
END {print GW/NR}' <file> | |||
</syntaxhighlight> | |||
Revision as of 13:53, 27 March 2018
- awk '{ for(i = 1; i <= NF; i++) { print $i; } }'
- Itterate over all fields
String manipulation
- substr(<string>,<start>,<num>)
- From <sting> return <num> characters, starting from <start>
- n=split(var,ARR,<fs>)
- Split var in array ARR, n holds the number of elements in ARR, <fs> is the field separator, if not given the variable FS is used as field separator (default white space). :Default action of awk for read line is NF=split(var,ARR," ")
NR++
$0=var
for ( i=1 ; i<=NF ; i++ ) {
$i=ARR[i]
}
- gsub(<regexp>,<string>,<variable>)
- Replace <regexp> with <string> in <variable>. Return number of replacements.
- <variable> is modified.
Calculations
Print average of field 4 for all records in <file> containing 'GW'
awk 'BEGIN {}
/GW/ {GW+=$4}
END {print GW/NR}' <file>