Convert space separated file to tab separated file

前端 未结 2 1161
一生所求
一生所求 2021-01-23 21:21

I was trying to use awk to convert a space delimited file into a tab delimited file. To my surprise this didn\'t work as expected:

awk -vOFS=$\'\\t\' \'{print}\'         


        
相关标签:
2条回答
  • 2021-01-23 21:42
    awk -v OFS='\t' '{$1=$1}1' file
    

    can be further truncated down to

    mawk 'BEGIN {OFS="\t"} (NF==1) || ($1=$1)' file.
    

    $1 = $1 isn't free. NF==1 will bypass it for any row that just happens to not have any spaces (just more flexible generic solution). Successful $1 = $1 returns true so the extra } 1' outside the braces is slightly superfluous.

    0 讨论(0)
  • 2021-01-23 21:48

    Try this:

    awk -v OFS='\t' '{$1=$1}1' file
    

    If you just set OFS, it does not do anything. By setting $1 to $1 it will use the OFS since field has changed. 1 is always true, so it will print the line. Same as {print}

    0 讨论(0)
提交回复
热议问题