How to reverse column order of a file in Linux from the command line

后端 未结 4 516
长发绾君心
长发绾君心 2021-01-04 03:59

I have a file named ip-list with two columns:

IP1    Server1
IP2    Server2

And I want to produce:

4条回答
  •  难免孤独
    2021-01-04 05:01

    The simplest solution is:

    awk '{print $2 "\t" $1}'
    

    However, there are some issues. If there may be white space in either of the fields, you need to do one of: (depending on if your awk supports -v)

    awk -v FS='\t' '{print $2 "\t" $1}'
    awk 'BEGIN{ FS="\t" } {print $2 "\t" $1}'
    

    Alternatively, you can do one of:

    awk -v OFS='\t' '{print $2,$1}'
    awk 'BEGIN{ OFS="\t" } {print $2,$1}'
    awk -v FS='\t' -v OFS='\t' '{print $2,$1}' # if allowing spaces in fields
    

    One of the comments asks, 'where does the filename go'? awk is used as a filter, so it would typically appear as:

    $ some-cmd | awk ... | other-cmd
    

    with no filename given. Or, a filename can be given as an argument after all commands:

    $ awk ... filename
    

提交回复
热议问题