How can I use cut to output the original string in a 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

      

Desired output after running a command like cut

or sed

(something that 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

      

+3


source to share


4 answers


One way 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)

      

+3


source


Through sed,



$ sed 's/^[^[:space:]]\+[[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+[^:]*:[[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+[^:]*:[[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+/\1:\2:\3:/;s/[[:space:]]\+/-/g' 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

      

0


source


A shorter version of awk would be like

$ awk -F[\ :]+ '{print $2":"$4":"$6":"$7"-"$8}' input
1.2.3.4:xxx:a:Q-W
5.6.7.8:yyy:b:X-Y
9.10.11.12:zzz:c:L-N

      

  • -F[\ :]+

    sets the field separator to space, or :

0


source


sed 's/  *[A-Z]: */:/g;s/...//;s/\(:[a-z]\)  */\1:/;s/  */-/g' YourFile

      

without further specification xxx

, yyy

...

0


source







All Articles