Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering Linux command output

Tags:

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.

Please help me on this issue.

Regards, Raaj

like image 535
Raajkumar Avatar asked Jan 17 '11 11:01

Raajkumar


People also ask

How do you filter command output?

You can use the | { begin | exclude | include } regular-expression option to filter the display command output.

How do I filter a command in Linux?

In Linux the grep command is used as a searching and pattern matching tools. The most common use of grep is to filter lines of text containing (or not containing) a certain string. You can write this without the cat. One of the most useful options of grep is grep -i which filters in a case insensitive way.

How do you filter grep output?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".

How do you filter top output?

To filter the top output to a specific process, press the O key and enter the entry as COMMAND=name, where the name refers to the process name. Press ENTER, and the top utility will filter the processes to systemd only. You can also highlight the specific process while keeping other processes in view.


2 Answers

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-----"

Quotes are optional but might prevent grep tripping over the -'s

like image 118
dtech Avatar answered Oct 23 '22 13:10

dtech


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

No need for cat here!

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.

like image 22
Johnsyweb Avatar answered Oct 23 '22 13:10

Johnsyweb