简体   繁体   English

Bash:如何更改文件的第一列和仅第一列

[英]Bash: how to change first column of a file and only the first column

I have a file that was screwed up by a program and now every line looks something like this: 我有一个被程序弄乱的文件,现在每一行看起来都像这样:

somelongstring:number   number    number   number   ... a lot more columns

(Tab delimited) What I need to do is modify every line such that the first column, if it is in the format somelengthystring:number, is changed to just number (get rid of the string and the colon) (制表符分隔)我需要做的是修改每一行,以使第一列(如果其格式为somelengthystring:number)更改为仅数字(摆脱字符串和冒号)

I know that I can use split in awk to get rid of the string and colon like: 我知道我可以在awk中使用split来摆脱字符串和冒号,例如:

awk '{
   split($1,array,":")
} 
END{
   print array[2],$2,$3...
}'

But the thing is that I don't want just the first column. 但事实是,我不想只关注第一列。 I want the entire line and just want the first column to be fixed. 我想要整行,只想固定第一列。 The only problem is that there are so many columns that it'd be rather stupid to type out $2,$3, ... all the way to $35 or whatever it is. 唯一的问题是,有如此多的列,以至于键入$ 2,$ 3,...一直到$ 35或其他任何值都是很愚蠢的。 What is a better way to fix this? 有什么更好的方法来解决此问题?

使用Perl,您可以执行以下操作:

cat file.txt | perl -pe 's/.*?://'

If what you have works so far, except for the $2, .... part: 如果到目前为止,您所拥有的东西仍然有效,除了$ 2,....部分:

awk '{
    split(..)
    $1=array[2]
    print
}'

Using sed . 使用sed Remove all characters from the beginning of the line ( ^ ) until first colon. 删除从行首( ^ )到第一个冒号的所有字符。

sed 's/^[^:]*://' infile

Using cut 使用cut

cut -d: -f2- file.txt

This uses the colon as a delimiter and keeps everything to the right of it. 这使用冒号作为分隔符,并将所有内容都保留在它的右边。

如果仅应更改第一个TAB分隔字段中的格式somelengthystring:number ,则可以尝试以下操作:

awk '$1~/:[0-9]*$/{sub(/.*:/,x,$1)}1' FS='\t' OFS='\t' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM