awk - KeynesYouDigIt/Knowledge GitHub Wiki
Basic Structure
pattern { action }
BEGIN pattern { action } { action } END pattern { action }
Print Options
print- The action to print/t- Tab- Invoke
awk -F,to comma-separate
Regex
word ~ /(first_word|second_word)/- Matchesword !~ /WORD/- Doesn't match
Scripting
'nestsexit- Early-exit the script
awk Syntax
#!/bin/awk -f
BEGIN { print "File\tOwner" }
{ print $8, "\t", $3}
END { print " - DONE -" }
bash Syntax
#!/bin/sh
awk '{print $'$column'}'
Variables
name="Kyle"- Assignment$0is the whole line$1,$4, etc. - Gives you each column$name- Named variable- Globals
- You can use more than one character
NF- Number of fieldsNR- Number of records, or the current recordORSRecord separatorFS- Column separatorFILENAME- Current filenameARGV[1]- An array of argumentsENVIRON["name"]- Array of variables
#!/bin/sh
column=${1:-1} # 1 is first variable passed in, -1 is default value
awk '{print $'$column'}'
Conditionals
#!/bin/awk
if (conditional){
} else if {
} else {
}
Loops
while ( conditional ) {
next
}
for ( expression ; conditional ; expression ) {
continue
}
for ( variable in array ) statement {
break
}
Functions
substr(string,position,length)split(string,array,separator)tolower(string)toupper(string)sub(/pattern/, replacement, string)match(string, pattern)RSTART- Index of startRLENGTH- Length of match
system("unix_command")- Returns exit codefunction(parameter){}
No input processing
#!/bin/awk -f
# Doesn't process any text
BEGIN {
print "File\tOwner"
exit;
}
Notes
- You can't interpolate variables in actions