I am trying to find a way, in bash, to turn a text with mutliple columns to appear as 1 column.
For example, I have a text file like this
Key1 Val1 Key4 Val4 Key7 Val7
Key2 Val2 Key5 Val5
Key3 Val3 Key6 Val6
and I want to turn this into
Key1 Val1
Key2 Val2
Key3 Val3
Key4 Val4
Key5 Val5
Key6 Val6
Key7 Val7
CodePudding user response:
You can do this with awk
, iterate over each field and add a new line every second word.
awk '{for(i=1; i<=NF; i ) {printf "%s ",$i; if(i%2==0 && i!=NF) print ""} print ""}
'
CodePudding user response:
You could try grep
with sort
$ grep -o '\<\S* \S*\>' input_file | sort -n
Key1 Val1
Key2 Val2
Key3 Val3
Key4 Val4
Key5 Val5
Key6 Val6
Key7 Val7
CodePudding user response:
Using awk:
$ awk -F" " '{ # double space delimiter
for(i=1;i<=NF;i ) # loop all fields
a[i]=a[i] (a[i]==""?"":ORS) $i # buffer to array a
}
END { # in the end
for(i=1;(i in a);i )
print a[i] # output the a array
}' file
Partial output:
Key1 Val1
Key2 Val2
Key3 Val3
Key4 Val4
...
Using sed:
$ sed 's/ /\n/g' file