Resources
- See this excellent [https://www.shortcutfoo.com/app/dojos/awk/cheatsheet cheat sheet].
Defining Functions
This example from [https://www.youtube.com/watch?v=jJ02kEETw70 Gary Explains on youtube]
func round(n) {
n = n + 0.5
n = int(n)
return n
}
/^w/ && $2>9000 { print $1,$2/1024,round($2/1024)"K" }
Line numbers and new files
The variable FNR is the current line number in the current file.
awk '/cout/ {print FILENAME ":" FNR ": " $0}' *.cpp
By comparing FNR to 1, we can detect a new file.
awk 'BEGIN {n=0} FNR==1 {n=n+1;print "New File: " FILENAME} END { print n " files" }' *.cpp
Joining some lines but not others
This joins each group of 5 lines using commas:
awk '{if((NR+1)%5 == 0) { print $0; } else { printf "%s, ",$0; }}'