AWK is a pattern-directed scanning and manipulating language, designed expecially for text processing.
It scans each input file for lines that match any of a set of patterns specified literally in prog or in one or more files specified as -f file. With each pattern there can be an associated action that will be performed when a line of a file matches the pattern.
It scans each input file for lines that match any of a set of patterns specified literally in prog or in one or more files specified as -f file. With each pattern there can be an associated action that will be performed when a line of a file matches the pattern.
A program basing on AWK is made of a list of rules that specify a pattern and the relative action to execute if the pattern is satisfied:
pattern { action }
Example usages.
Suppose you have this file.txt:
Red Blue 1
Orange Pink 2
Yellow Black 3
Green White 4
Red Purple 5
- Print the lines from file.txt that contains the word "Blue"
$ awk '/Blue/ { print }' file.txtRed Blue 1
- Print the whole file:
$ awk '{print $0}' file.txtRed Blue 1Orange Pink 2Yellow Black 3Green White 4Red Purple 5
- Print the first column of the file:
$ awk '{print $1}' file.txt
RedOrangeYellowGreenRed
- Print the second column of the file:
$ awk '{print $2}' file.txt
BluePinkBlackWhitePurple
- Preprocessing: add an header to your output:
$ awk 'BEGIN {print "Second column:"} {print $2}' file.txt
Second column:BluePinkBlackWhitePurple
- Postprocessing: add a footer to your output:
$ awk '{print $2} END {print "End of file!"}' file.txtBluePinkBlackWhitePurpleEnd of file!
- Substitution: change the field separator (FS) with an output field separator (OFS) in file:
$ awk 'BEGIN{FS=" "; OFS="-"} {print $1,$2,$3}' file.txtRed-Blue-1Orange-Pink-2Yellow-Black-3Green-White-4Red-Purple-5
No comments:
Post a Comment