Very helpful to manipulate text files quickly. I don't know much, but this little list of one-liners makes things pretty clear for some basic tasks.
A Handful of Useful awk One-Liners
Although awk can be used to write programs of some complexity, many useful programs are not complicated. Here is a collection of short programs that you might find handy and/or instructive. To run the program from the command line, on a single file named "filename", type: awk 'program' filename where program is the text in the following examples.
Source: The AWK Programming Language
- Print the total numnber of input lines:
END { print NR }- Print the tenth input line:
NR == 10
- Print the last field of every input line:
{ print $NF }- Print the last field of the last input line:
{ field = $NF} END { print field }- Print every input line with more than 4 fields:
NF > 4- Print every input line in which the last field is more than 4:
$NF > 4- Print the total number of fields in all input lines:
{ nf = nf + NF } END { print nf }- Print the total number of lines that contain Beth:
/Beth/ { nlines = nlines + 1 } END { print nlines }
- Print the largest first fields and the line that contains it ( assumes some $1 is positive):
$1 > max { max = $1 ; maxlines = $0 } END { print max, maxline)
- Print every line that has at least one field:
NF > 0
- Pritn every line longer than 80 characters:
length($0) > 80
- Print the numer of fields in every line, followed by the line itself:
{ print NF, $0 }
- Print the first two fields, in opposite order, of every line:
{ print $2, $1 }
- Exchange the first two fields of every line and then print the line:
{ temp = $1 ; $1 = $2 ; $2 = temp ; print }
- Print every line witg rge first field replaced by the line number:
{ $1 = NR ; print }
- Print every line after erasing the second field:
{ $2 = ""; print }
- Print in reverse order the fields of every line:
{ for (i=NF ; i>0 ; i=i-1) printf( "%s ", $i) printf("n") }
- Print the sums of the fields of every line:
{ sum = 0 for ( i=1 ; i<=NF ; i=i+1) sum = sum + $i print sum }
- Add up all fields in all lines and print the sum:
{ for ( i=1 ; i<=NF ; i=i+1 ) sum = sum + $i} END { print sum }
- Print every line after replacing each field by its absolute value:
{ for (i=1 ; i<=NF ; i=i+1) if ($i<0) $i=-$i print }