Rearrange columns using cut

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

    Expanding on the answer from @Met, also using Perl:
    If the input and output are TAB-delimited:

    perl -F'\t' -lane 'print join "\t", @F[1, 0]' in_file
    

    If the input and output are whitespace-delimited:

    perl -lane 'print join " ", @F[1, 0]' in_file
    

    Here,
    -e tells Perl to look for the code inline, rather than in a separate script file,
    -n reads the input 1 line at a time,
    -l removes the input record separator (\n on *NIX) after reading the line (similar to chomp), and add output record separator (\n on *NIX) to each print,
    -a splits the input line on whitespace into array @F,
    -F'\t' in combination with -a splits the input line on TABs, instead of whitespace into array @F.

    @F[1, 0] is the array made up of the 2nd and 1st elements of array @F, in this order. Remember that arrays in Perl are zero-indexed, while fields in cut are 1-indexed. So fields in @F[0, 1] are the same fields as the ones in cut -f1,2.

    Note that such notation enables more flexible manipulation of input than in some other answers posted above (which are fine for a simple task). For example:

    # reverses the order of fields:
    perl -F'\t' -lane 'print join "\t", reverse @F' in_file
    
    # prints last and first fields only:
    perl -F'\t' -lane 'print join "\t", @F[-1, 0]' in_file
    

提交回复
热议问题