How do I find a text string using awk?
Posted by on 2014-09-19 14:05:37:
grep will find a specific string of text in a file, but awk gives you the ability to isolate a particular column of text.
For example, we have a text file with the following content in a file called test.txt:
This is a line of text demonstrating the use of awk.
So, running the following command:
cat test.txt |awk -F " " '{print $2}'
- will yield the following output.is
So what have we done here? We have piped the file test.txt into awk, and by using the -F parameter, have set " " (space) as the delimiter to use.
And '{print $2}' tells awk to print the text after the second space in the row.
We could for example have another file, using the "-" instead of space as a delimiter.
This-is-a-line-of-text-demonstrating-the-use-of-awk.
Running the command:
cat test.txt |awk -F "-" '{print $4}'
will print the following text string:line
So this time we specified "-" as the delimiter.
Try this for yourself with differing strings in the text file, and different delimiters.
You can also mix delimiters.
Tags: AWK , Linux
Return to home page: Home