In my early days of getting used to the Linux command line, I was intimidated by sed and awk examples and didn't even try to learn them. Hopefully, this gentler introduction works for you and the various syntactical magic has been explained adequately. Try to experiment with the given examples, for example change field number to something other than the number used. Be curious, like what happens if field number is negative or a floating-point number. Read the manual. Practice a lot.
Next chapter is dedicated solely for regular expressions. The features introduced in this chapter would be used in the examples, so make sure you are comfortable with awk syntax before proceeding. And, do solve the exercises coming up in the next section.
Exercises
Exercise related files are available from exercises folder of learn_gnuawk repo. All the exercises are also collated together in one place at Exercises.md. For solutions, see Exercise_solutions.md.
a)For the input file addr.txt, display all lines containing is.
$ cat addr.txt Hello World How are you This game is good Today is sunny 12345 You are funny $ awk ##### add your solution here This game is good Today is sunny
b) For the input file addr.txt, display first field of lines not containing y. Consider space as the field separator for this file.
$ awk ##### add your solution here Hello This 12345
c) For the input file addr.txt, display all lines containing no more than 2 fields.
$ awk ##### add your solution here Hello World 12345
d) For the input file addr.txt, display all lines containing is in the second field.
$ awk ##### add your solution here Today is sunny
e) For each line of the input file addr.txt, replace first occurrence of o with 0.
$ awk ##### add your solution here Hell0 World H0w are you This game is g0od T0day is sunny 12345 Y0u are funny
f) For the input file table.txt, calculate and display the product of numbers in the last field of each line. Consider space as the field separator for this file.
$ cat table.txt brown bread mat hair 42 blue cake mug shirt -7 yellow banana window shoes 3.14 $ awk ##### add your solution here -923.16
g) Append . to all the input lines for the given stdin data.
$ printf 'last\nappend\nstop\ntail\n' | awk ##### add your solution here last. append. stop. tail.