Rearrange columns using cut

后端 未结 8 1539
难免孤独
难免孤独 2020-11-28 03:53

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

8条回答
  •  不知归路
    2020-11-28 04:40

    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
      

提交回复
热议问题