I am currently working with some text files from which I have to extract some data. Generally, when you have to do this kind of work on a *nix machine, you use cut or awk. However, even for simple tasks cut is superseded by the mighty awk. Let’s look at the following examples which are closely related to the data that I’m working with. Assume we have the following text file:
1 2 3 4 5 | |
What I’d like to do is to extract the strings from each line and assign them to some parameters; obviously the second parameter can be null. To do this with cut you’d have to use two different call types, one for each parameter:
1 2 3 4 5 6 7 8 | |
Notice the -s option in the second call. This tells cut not to print lines not containing delimiters. If by mistake you’d forget to add that flag to the options list, the output would be this:
1 2 3 4 5 | |
which includes the values for the first parameter too. Not good.
Now let’s share some awk love:
1 2 3 4 5 6 7 8 9 10 | |
Of course, if your restrictions aren’t like mine you can as well use cut. However, you’d be safer with awk.
Happy Bash parsing!