I am having a file in the following format
Column1 Column2 str1 1 str2 2 str3 3
I want the columns to be rearranged. I tried below
using just the shell,
while read -r col1 col2
do
echo $col2 $col1
done <"file"
Using join
:
join -t $'\t' -o 1.2,1.1 file.txt file.txt
Notes:
-t $'\t'
In GNU join
the more intuitive -t '\t'
without the $
fails, (coreutils v8.28 and earlier?); it's probably a bug that a workaround like $
should be necessary. See: unix join separator char.
join
needs two filenames, even though there's just one file being worked on. Using the same name twice tricks join
into performing the desired action.
For systems with low resources join
offers a smaller footprint than some of the tools used in other answers:
wc -c $(realpath `which cut join sed awk perl`) | head -n -1
43224 /usr/bin/cut
47320 /usr/bin/join
109840 /bin/sed
658072 /usr/bin/gawk
2093624 /usr/bin/perl