Cut command output

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

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 shellscript with: ./ myscript test2 In this script I need the identifier test2 (shown in the command "xm list" (ID33)) I tried it with grep and cut it like this:

 xm list | grep $1 | cut ??? 

How it works?

+4
source share
4 answers

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

 xm <subcommand> [args] 

domid domain name

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

Have you tried xm domid test2 ?

+2
source

How about using awk?

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

I added ^ to /^test/ to check this text at the beginning of the line. Also awk '$1=="test2" {print $2}' will do this.

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 
+4
source

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

Use awk as in another answer, or use tr to β€œcompress” spaces before using cut :

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

This will not work:

Can only be done with grep:

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

Grep on my phone does not know the -P flag, so I can’t check it right now, but this should work.

But this works fine:

Ok, the previous code doesn't work, yes. I also tried to get the fourth column instead of the second.
But still I insist that this can be done with grep !

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

This code has been tested and works :)
The point here is that \K will reset the previously agreed text.

0
source

Source: https://habr.com/ru/post/1501807/


All Articles