Vince
Vince

Reputation: 1133

Cut the output of a command

I have the following output of the command "xm list":

Name                                        ID   Mem VCPUs      State   Time(s)
Domain-0                                     0   505     4     r-----  11967.2
test1                                       28  1024     1     -b----    137.9
test2                                       33  1024     1     -b----      3.2

I execute a shellscript with: ./myscript test2 In this script, I need the ID of test2 (shown at the command "xm list" (ID33)) I tried it with grep and cut like this:

xm list | grep $1 | cut ???

How does this work?

Upvotes: 4

Views: 3296

Answers (4)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10683

This is not going to work:

Can be done just with grep:

xm list | grep -P -o '(?<=^([^ ]+ ){3}).*$'

Grep on my phone doesn't know -P flag, so I can't test it right now, but this should work.

But this works perfectly:

Ok, previous code doesn't work, yes. Also I was trying to get the 4th column instead of 2nd.
But still, I insist that it can be done with grep!

xm list | grep -P -o '^test2\s+\K[^ ]+'

This code is tested and it works :)
The point here is that \K will reset previously matched text.

Upvotes: 0

jon
jon

Reputation: 6246

http://linux.die.net/man/1/xm

xm <subcommand> [args]

domid domain-name

Converts a domain name to a domain id using xend's internal mapping.

Have you tried xm domid test2 ?

Upvotes: 2

fedorqui
fedorqui

Reputation: 290525

What about using awk?

xm list | awk '/^test2/ {print $2}'

I added ^ in /^test/ so that it checks this text in the beginning of the line. Also awk '$1=="test2" {print $2}' would make it.

Test

$ cat a
Name                                        ID   Mem VCPUs      State   Time(s)
Domain-0                                     0   505     4     r-----  11967.2
test1                                       28  1024     1     -b----    137.9
test2                                       33  1024     1     -b----      3.2
$ awk '/^test2/ {print $2}' a
33

Upvotes: 5

dogbane
dogbane

Reputation: 274898

With cut you cannot treat multiple consecutive delimiters as one, so cut -d ' ' will not work.

Either use awk as in the other answer, or use tr to "squeeze" the spaces before using cut:

xm list | grep test2 | tr -s ' ' | cut -d ' ' -f2

Upvotes: 4

Related Questions