Bash Awk不适用于第一行

Bash Awk不适用于第一行,bash,awk,Bash,Awk,大家好 请您帮我解决一些文件准备问题: 我有一个文件: 2:1 3:1 4:2 5:1 7:2 34:1 37:3 ... 4:2 6:1 8:1 23:1 25:2 30:1 ... 我想得到: 20002:1 20003:1 20004:2 20005:1 20007:2 20034:1 20037:3 ... 20004:2 20006:1 20008:1 20023:1 20025:2 20030:1 ... 我试过: awk '{FS=":"; RS=" "; OFS=":";

大家好

请您帮我解决一些文件准备问题:

我有一个文件:

2:1 3:1 4:2 5:1 7:2 34:1 37:3 ...
4:2 6:1 8:1 23:1 25:2 30:1 ...
我想得到:

20002:1 20003:1 20004:2 20005:1 20007:2 20034:1 20037:3 ... 
20004:2 20006:1 20008:1 20023:1 20025:2 20030:1 ...
我试过:

awk '{FS=":"; RS=" "; OFS=":"; ORS=" "}{$1=$1+20000; print $0}' 
但它只能部分工作:它不适用于第一行,给出
20002:1:3:1:4:2..
,也不适用于每行的第一个元素,给出
4:2 20006:1 20008:1…
您可以使用它(GNU awk仅用于RT)

解释

BEGIN{
#Only run at start of script
FS=OFS=":"
#Set input and output field separator to :
RS="[[:space:]]"
#Set the record separator to any space character e.g `\n` `\t` or  ` `
}


{ORS=RT
#Set the output record separator to whatever was captured by the input one, i.e keep newline space or tab in the right places
$1+=20000; print
#Do your math and print, note that `+=` is shorthand for adding to the current value, 
#and also that print can be used on it's own as by default it prints $0(you can also use 1 
#at the end of the script as this evaluates to true and the default action if no block
#is defined is to print the current line)
}'
您可以使用它(GNU awk仅用于RT)

解释

BEGIN{
#Only run at start of script
FS=OFS=":"
#Set input and output field separator to :
RS="[[:space:]]"
#Set the record separator to any space character e.g `\n` `\t` or  ` `
}


{ORS=RT
#Set the output record separator to whatever was captured by the input one, i.e keep newline space or tab in the right places
$1+=20000; print
#Do your math and print, note that `+=` is shorthand for adding to the current value, 
#and also that print can be used on it's own as by default it prints $0(you can also use 1 
#at the end of the script as this evaluates to true and the default action if no block
#is defined is to print the current line)
}'

如果没有@123更优雅的解决方案所要求的GNU awk:

$ awk -F"[: ]+" '{for(i=1;i<NF;i+=2){$i+=20000; printf "%s:%s ",$i,$(i+1)} print ""}' cs.txt

20002:1 20003:1 20004:2 20005:1 20007:2 20034:1 20037:3 
20004:2 20006:1 20008:1 20023:1 20025:2 20030:1 

$awk-F“[:]+”{for(i=1;i如果没有@123更优雅的解决方案所要求的GNU awk:

$ awk -F"[: ]+" '{for(i=1;i<NF;i+=2){$i+=20000; printf "%s:%s ",$i,$(i+1)} print ""}' cs.txt

20002:1 20003:1 20004:2 20005:1 20007:2 20034:1 20037:3 
20004:2 20006:1 20008:1 20023:1 20025:2 20030:1 

$awk-F“[:]+”{for(i=1;i@EdMorton我知道,但OP已经提供了该代码,它确实可以工作(即使不是以最简单的方式),然后我想最好还是离开它。@EdMorton我认为好处不是解释得太多,只是解释了那些会导致它不工作的部分,而不是那些看起来不太好的部分。不过我会编辑。@EdMorton也许,他们现在已经在那里了。也许我只是有点懒。@EdMorton我知道,但OP已经有了p提供了该代码,它确实有效(即使不是以最简单的方式),然后我想最好还是离开它。@EdMorton我认为好处不是解释得太多,只是解释了那些会导致它不工作的部分,而不是那些看起来不太好的部分。不过我会编辑。@EdMorton也许,反正他们现在在里面。也许我只是有点懒。