Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut the output of a command

Tags:

linux

grep

bash

cut

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?

like image 452
Vince Avatar asked Dec 20 '22 00:12

Vince


2 Answers

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
like image 118
fedorqui 'SO stop harming' Avatar answered Jan 07 '23 09:01

fedorqui 'SO stop harming'


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
like image 38
dogbane Avatar answered Jan 07 '23 08:01

dogbane