Search code examples
linuxbashawksedcut

How do I use cut to output initial line in different format?


I have a file like this:

A: 1.2.3.4       Z: xxx             R: a              Q W
A: 5.6.7.8       Z: yyy             R: b              X Y
A: 9.10.11.12    Z: zzz             R: c              L N X

The desired output after running command like cut or sed (something which exists in 99% of Linux environments):

1.2.3.4:xxx:a:Q-W
5.6.7.8:yyy:b:X-Y
9.10.11.12:zzz:c:L-N-X

Solution

  • One way with awk:

    $ awk '{printf "%s:%s:%s:",$2,$4,$6;for(i=7;i<NF;i++)printf "%s-",$i;print $NF}' file 
    1.2.3.4:xxx:a:Q-W
    5.6.7.8:yyy:b:X-Y
    9.10.11.12:zzz:c:L-N-X
    

    Explanation:

    The script will run for every line in the file:

    printf "%s:%s:%s:",$2,$4,$6;    # print the 2nd, 4th, 6th field separated by a :
    for(i=7;i<NF;i++)               # from the 7th field to the penultimate field
    printf "%s-",$i;                # print the field value followed by a -
    print $NF                       # print the last field (followed by a newline)