Raajkumar
Raajkumar

Reputation: 897

Filtering Linux command output

I need to get a row based on column value just like querying a database. I have a command output like this:

Name  ID  Mem VCPUs      State   Time(s)

Domain-0   0  15485  16       r----- 1779042.1

prime95-01                512     1       -b----  61.9

Here I need to list only those rows where state is "r". Something like this,

Domain-0               0  15485  16       r----- 1779042.1

I have tried using "grep" and "awk" but still I am not able to succeed.

Upvotes: 34

Views: 106063

Answers (5)

johnsyweb
johnsyweb

Reputation: 141928

grep can handle this for you:

yourcommand | grep -- 'r-----'

It's often useful to save the (full) output to a file to analyse later. For this I use tee.

yourcommand | tee somefile | grep 'r-----'

If you want to find the line containing "-b----" a little later on without re-running yourcommand, you can just use:

grep -- '-b----' somefile

I recommend putting -- after your call to grep since your patterns contain minus-signs and if the minus-sign is at the beginning of the pattern, this would look like an option argument to grep rather than a part of the pattern.

Upvotes: 5

dtech
dtech

Reputation: 14070

There is a variaty of tools available for filtering.

If you only want lines with "r-----" grep is more than enough:

command | grep "r-----"

Or

cat filename | grep "r-----"

Upvotes: 35

Anoop Kumar
Anoop Kumar

Reputation: 1

Filtering by awk cmd in linux:-

Firstly find the column for this cmd and store file2 :-

awk '/Domain-0 0 15485 /' file1 >file2

Output:-

Domain-0 0 15485 16 r----- 1779042.1

after that awk cmd in file2:-

awk '{print $1,$2,$3,$4,"\n",$5,$6}' file2

Final Output:-

Domain-0 0 15485 16

r----- 1779042.1

Upvotes: 0

Patrick Echterbruch
Patrick Echterbruch

Reputation: 679

grep solution:

command | grep -E "^([^ ]+ ){4}r"

What this does (-E switches on extended regexp):

The first caret (^) matches the beginning of the line. [^ ] matches exactly one occurence of a non-space character, the following modifier (+) allows it to also match more occurences.

Grouped together with the trailing space in ([^ ]+ ), it matches any sequence of non-space characters followed by a single space. The modifyer {4} requires this construct to be matched exactly four times.

The single "r" is then the literal character you are searching for.

In plain words this could be written like "If the line starts <^> with four strings that are followed by a space <([^ ]+ ){4}> and the next character is , then the line matches."

A very good introduction into regular expressions has been written by Jan Goyvaerts (http://www.regular-expressions.info/quickstart.html).

Upvotes: 3

trojanfoe
trojanfoe

Reputation: 122458

try:

awk '$5 ~ /^r.*/ { print }' 

Like this:

cat file | awk '$5 ~ /^r.*/ { print }' 

Upvotes: 3

Related Questions