Convert space separated file to tab separated file

Deadly 提交于 2021-02-05 08:41:32

问题


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}' column.txt
item                 gram
tomato                500
orange               1500
bread                2000

I was expecting something like this:

item    gram
tomato  500
orange  1500
bread   2000

What am I missing ?

Note: many have suggested several alternatives, here are some of them maybe someone is interested.

tr -s " " "\t" <column.txt

column -t <column.txt

perl -ple "s/\s+/\t/g" <column.txt

sed "s/\s\+/\t/" <column.txt

ruby -ple 'gsub(/\s+/,"\t")' <column.txt

python -c "import sys,re; [ sys.stdout.write(re.sub(r' +','\t',l)) for l in sys.stdin ]" <column.txt

回答1:


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}




回答2:


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.



来源:https://stackoverflow.com/questions/57945801/convert-space-separated-file-to-tab-separated-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!