Home > Mobile >  Using AWK, print $1 (First column) if the string in the column starts with a specific string?
Using AWK, print $1 (First column) if the string in the column starts with a specific string?

Time:04-07

Firstly I would like to say that I am aware of the many questions here on StackOverflow regarding AWK and regular expressions. I already tried searching different questions and answer, tested multiple answers and none worked.

I have a list that is generated by the command:

iostat -dx | awk ' { print $1 }'

It outputs the following:

extended
device
ada0
ada1
ada2
pass0
pass1
pass2

I want to output only the lines starting with ada... ada0, ada1, ada2.

Here are some commands I tried, and they all output nothing:

iostat -dx | awk '($1 == "^ada") { print $1 }'
iostat -dx | awk '($1 == "/^ada.*$/") { print $1 }'

This one outputs device (??):

iostat -dx | awk '($1 ~ /^d[ada]*/ ) { print $1 }'

Important: I can not use grep for this, since this is being runned on a Docker Image that DOES NOT have GREP, only AWK. I am very much aware of the command "iostat -x | grep "ada" | awk '{print $1}'", but unfortunatelly I can not use that.

CodePudding user response:

The regular expression should just be ^ada, as in your first attempt. But the regexp should be inside //, not quotes, and you have to use ~ to compare it.

iostat -dx | awk '$1 ~ /^ada/ { print $1 }'

CodePudding user response:

I am very much aware of the command "iostat -x | grep "ada" | awk '{print $1}'", but unfortunatelly I can not use that.

Just replacing grep "ada" using awk in above gives

iostat -x | awk '/ada/' | awk '{print $1}'

which might be written more concisely as

iostat -x | awk '/ada/{print $1}'

Note that this will print all lines containing ada anywhere, like that with grep you have shown.

As side note if grep is prohibited you might replace simple grep commands using awk as shown above or using sed as follows

iostat -x | sed -n '/ada/p' | awk '{print $1}'

-n does turn off default printing, /ada/p means if line contains ada do print it

  • Related