When it comes to command line text processing, from an abstract point of view, there are three major pillars



Download 125.91 Kb.
Page33/60
Date09.03.2023
Size125.91 Kb.
#60849
1   ...   29   30   31   32   33   34   35   36   ...   60
Learn GNU AWK

Summary


This chapter discussed about the -i inplace option which is useful when you need to edit a file in-place. This is particularly useful in automation scripts. But, do ensure that you have tested the awk command before applying to actual files if you need to use this option without creating backups.
The next chapter will revisit the use of shell variables in awk commands.

Exercises


a) For the input file copyright.txt, replace copyright: 2018 with copyright: 2020 and write back the changes to copyright.txt itself. The original contents should get saved to copyright.txt.orig
$ cat copyright.txt bla bla 2015 bla blah 2018 blah bla bla bla copyright: 2018 $ awk ##### add your solution here $ cat copyright.txt bla bla 2015 bla blah 2018 blah bla bla bla copyright: 2020 $ cat copyright.txt.orig bla bla 2015 bla blah 2018 blah bla bla bla copyright: 2018
b) For the input files nums1.txt and nums2.txt, retain only second and third lines and write back the changes to their respective files. No need to create backups.
$ cat nums1.txt 3.14 4201 777 0323012 $ cat nums2.txt -45.4 -2 54316.12 0x231 $ awk ##### add your solution here $ cat nums1.txt 4201 777 $ cat nums2.txt -2 54316.12

Using shell variables


When it comes to automation and scripting, you'd often need to construct commands that can accept input from user, file, output of a shell command, etc. As mentioned before, this book assumes bash as the shell being used.
As an example, see my repo ch: command help for a practical shell script, where commands are constructed dynamically.

-v option


The most common method is to use the -v command line option.
$ # assume that the 's' variable is part of some bash script $ # or perhaps a variable that has stored the output of a shell command $ s='cake' $ awk -v word="$s" '$2==word' table.txt blue cake mug shirt -7

Download 125.91 Kb.

Share with your friends:
1   ...   29   30   31   32   33   34   35   36   ...   60




The database is protected by copyright ©ininet.org 2024
send message

    Main page