Rearrange columns using cut

后端 未结 8 1544
难免孤独
难免孤独 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:30

    You can use Perl for that:

    perl -ane 'print "$F[1] $F[0]\n"' < file.txt
    
    • -e option means execute the command after it
    • -n means read line by line (open the file, in this case STDOUT, and loop over lines)
    • -a means split such lines to a vector called @F ("F" - like Field). Perl indexes vectors starting from 0 unlike cut which indexes fields starting form 1.
    • You can add -F pattern (with no space between -F and pattern) to use pattern as a field separator when reading the file instead of the default whitespace

    The advantage of running perl is that (if you know Perl) you can do much more computation on F than rearranging columns.

提交回复
热议问题