将空格分隔的文件转换为制表符分隔的文件 [英] Convert space separated file to tab separated file

查看:48
本文介绍了将空格分隔的文件转换为制表符分隔的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用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}

这篇关于将空格分隔的文件转换为制表符分隔的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆