Issue
I have files with data, but some lines have the data in the wrong order:
name cat
value 7.25 label X
value 1.13 label 2
value 15.75 label 1
name dog
label 1 value 20.00
label X value 9.00
label 2 value 1.10
name cow
value 1.10 label 2
value 8.25 label X
value 19.00 label 1
name sheep
value 1.11 label 2
value 8.80 label X
value 19.00 label 1
name mouse
value 1.13 label 2
value 8.00 label X
value 19.00 label 1
name donkey
value 1.05 label 2
value 9.50 label X
value 16.00 label 1
name dog
label 1 value 20.00
label X value 9.00
label 2 value 1.10
As you can see some lines start with label * , and some lines start with value * ,
I wish to swap the order of the strings when the line begins with 'value' so all lines (ignoring the line containing name) are in this format 'Label * value *'
Desired Output:
name cat
label X value 7.25
label 2 value 1.13
label 1 value 15.75
name dog
label 1 value 20.00
label X value 9.00
label 2 value 1.10
name cow
label 2 value 1.10
label X value 8.25
label 1 value 19.00
name sheep
label 2 value 1.11
label X value 8.80
label 1 value 19.00
name mouse
label 2 value 1.13
label X value 8.00
label 1 value 19.00
name donkey
label 2 value 1.05
label X value 9.50
label 1 value 16.00
name dog
label 1 value 20.00
label X value 9.00
label 2 value 1.10
I have tried writing a loop, grepping for lines that start with 'value' , however i am not sure on the next steps.
How can i acheive this?
Solution
This job is pretty much a perfect fit for awk
:
awk '$1 == "value" { print $3, $4, $1, $2; next; } 1'
awk
programs consist of condition/operation pairs; the code inside the first block is run only if $1 == "value"
is true, reversing the operations in that case; the 1
is a bare condition (which thus gets a default operation of printing the whole line, which runs whenever the first condition was not run (with its next
command causing flow control to skip directly to the next line of input).
Answered By - Charles Duffy