This is an old revision of the document!
awk ' { if ( length > x ) { x = length } }END{ print x }' file.txt
awk
can be used for complex calculations, for example:
awk 'BEGIN {printf "%.3f\n", sin(30 * atan2(0, -1)/180)}'
will calculate and return:
0.500
Since awk
does not have a constant for , we use atan2(0, -1)
instead.
Suppose you have a file input
containing data separated by delimiters such as:
variable = value
or:
variable = value
The following command can be used to obtain value
:
awk -F"[ \t]*[=][ \t]*" '{ print $2 }' input
To remove all duplicates from file.txt
without sorting, issue:
awk '!x[$0]++' file.txt
Given a file with the contents:
Q: What is this? A: This is a FAQ!
and you would like to achieve:
Q: What is this? A: This is a FAQ!
then the following awk
one liner:
awk 'NR%2{printf "%s ",$0;next;}1' yourFile
will merge all the lines in a file by two.
Given an input such as:
a1 : "abc c2 : def e3 : "ghi " f5 :" a b"
The following awk script:
awk -F: ' function trim(s) { return gensub(/^[ \t"]*|[ \t"]*$/, "", "g", s) } BEGIN { printf "{" } NR > 1 { printf(", ") } { printf("\"%s\":\"%s\"", trim($1), trim(substr($0, index($0,":") + 1))); } END { print "}" } '
will return the JSON object:
{"a1":"abc","c2":"def","e3":"ghi","f5":"a b"}
where keys and values are trimmed for spaces and quotes from the start and end.
One example application would be creating a JSON object out of the status of an APC UPS:
apcaccess | awk -F: ' function trim(s) { return gensub(/^[ \t"]*|[ \t"]*$/, "", "g", s) } BEGIN { printf "{" } NR > 1 { printf(", ") } { printf("\"%s\":\"%s\"", trim($1), trim(substr($0, index($0,":") + 1))); } END { print "}" } '