且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用awk将列中的值替换为txt文件中的另一个值

更新时间:2023-01-07 15:58:00

困难在于,与sed不同,awk不会告诉我们何时进行最后一行的操作.这是一种解决方法:

The difficulty is that, unlike sed, awk does not tell us when we are working on the last row. Here is one work-around:

$ awk 'NR>1{print last} {last=$0} END{$0=last;$2=$5+1;print}' OFS='\t' file.txt
AAA     134     145     Sat     150     167
AAA     156     167     Sat     150     167
AAA     151     187     Sat     150     167

这可以通过将前一行保留在变量 last 中来实现.更详细地:

This works by keeping the previous line in the variable last. In more detail:

  • NR> 1 {最后打印}

对于除第一行以外的每一行,打印 last .

For every row, except the first, print last.

last = $ 0

更新 last 的值.

END {$ 0 = last;$ 2 = $ 5 + 1;打印}

到达文件末尾时,更新字段2并打印.

When we have reached the end of the file, update field 2 and print.

OFS ='\ t'

将输出的字段分隔符设置为选项卡.

Set the field separator on output to a tab.

此方法读取文件两次,第一次计数行数,第二次更改最后一行.因此,这效率较低,但可能更容易理解:

This approach reads the file twice, first to count the number of lines and the second time to change the last row. Consequently, this is less efficient but it might be easier to understand:

$ awk -v n="$(wc -l <file.txt)" 'NR==n{$2=$5+1} 1' OFS='\t' file.txt
AAA     134     145     Sat     150     167
AAA     156     167     Sat     150     167
AAA     151     187     Sat     150     167

改为更改第一行

$ awk 'NR==1{$2=$5+1} 1' OFS='\t' file.txt
AAA     151     145     Sat     150     167
AAA     156     167     Sat     150     167
AAA     175     187     Sat     150     167

更改第一行和最后一行

$ awk 'NR==1{$2=$5+1} NR>1{print last} {last=$0} END{$0=last;if(NR>1)$2=$5+1;print}' OFS='\t' file.txt
AAA     151     145     Sat     150     167
AAA     156     167     Sat     150     167
AAA     151     187     Sat     150     167