Search code examples
linuxbashstring-parsing

Parse all column elements from a linux bash command output


I would like to parse the column elements of the output from the command lsscsi.

Here is a sample output,

# lsscsi

[0:0:0:0]   disk   ATA   VBOX HARDDISK   1.0   /dev/sda
[0:0:1:0]   disk   ATA   VBOX HARDDISK   1.0   /dev/sdb
[1:0:1:0]   disk   ATA   VBOX HARDDISK   1.0   /dev/sdc

Example if I want column 2, my output should be,

disk
disk
disk

If cloumn 7,

/dev/sda
/dev/sdb
/dev/sdc

Thanks


Solution

  • Use awk like this:

    awk -v col=7 '{print $col}' file
    

    Or to print 2 columns:

    awk -v col1=2 -v col2=7 '{print $col1, $col2}' file
    

    OR to make it print multiple columns using a colon delimited list:

    awk -v col='2:7' '
    BEGIN {n = split (col, arr, /:/)}
    n {
       for (i=1; i in arr; ++i)
          printf "%s%s", $arr[i], (i < n ? OFS : ORS)
    }' file