Posted: . At: 11:12 AM. This was 4 years ago. Post ID: 13995
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.



Sponsored



Very useful bash awk scripting tricks.


Awk and bash are a very good combination for extracting certain text strings from a text file or the output of a program. Here I am extracting only the values that are surrounded by square brackets.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ lspci | awk -vRS="]" -vFS="[" '{print $2}'
AHCI mode
GeForce GTX 1050

This would work for round brackets as well, just edit the one-liner.

In this example, I am returning only one value that is in square brackets.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ lspci | grep VGA | cut -d "[" -f2 | cut -d "]" -f1
GeForce GTX 1050

This could be a very useful trick for filtering text from any output.

In this example, I am looking for values between round brackets.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ lspci | grep VGA | cut -d "(" -f2 | cut -d ")" -f1
rev a1

This is another example, printing the values between square brackets, but only printing a number of results less than 2.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ lspci | awk -v RS=[ -v FS=] 'NR>2{print $1}'
GeForce GTX 1050

Another good usage of awk. Print out the GPU name easily from the command line.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ nvidia-settings -g | awk '/GeForce/{print $4,$5,$6}'
GeForce GTX 1050/PCIe/SSE2

Finally, this can allow me to find the certain value I am looking for, and also print only certain columns in the line of text.

4.4 Mon Jan 27 jason@Yog-Sothoth 0: $ lspci | awk '/GeForce/{print $8,$9,$10}'
[GeForce GTX 1050]

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.