将空格分隔的文件转换为制表符分隔的文件
问题描述:
我试图使用awk将以空格分隔的文件转换为制表符分隔的文件.令我惊讶的是,这没有按预期进行:
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
我期待着这样的事情:
item gram
tomato 500
orange 1500
bread 2000
我想念什么?
注意:许多人提出了几种替代方案,其中一些可能有人感兴趣.
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
答
尝试一下:
awk -v OFS='\t' '{$1=$1}1' file
如果仅设置OFS,则不会执行任何操作.通过将 $ 1
设置为 $ 1
,由于字段已更改,它将使用OFS. 1
始终为true,因此它将打印该行.与 {print}
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}