使用awk将列中的值替换为txt文件中的另一个值 [英] Replacing value in column with another value in txt file using awk
问题描述
我是linux和awk脚本的新手.我有如下所示的tab delim txt文件:
I am new to linux and awk scripting. I have tab delim txt file like follows:
AAA 134 145 Sat 150 167
AAA 156 167 Sat 150 167
AAA 175 187 Sat 150 167
我只想将最后一行第二列(175)中的值替换为最后一行第五列(150 + 1)中的值,这样我的最终输出应类似于
I would like replace only the value in last row, second column(175) with the value in the last row,5th column(150+1) so that my final output should look like
AAA 134 145 Sat 150 167
AAA 156 167 Sat 150 167
AAA 151 187 Sat 150 167
我尝试了 awk'$ 2 = $ 5 + 1'file.txt
,但是它更改了第二列中我不需要的所有值.我只想用150(+1)代替175.请指导我
I tried awk '$2=$5+1' file.txt
but it changes all the values in second column which I don't want. I want replace only 175 with 150(+1). Kindly guide me
推荐答案
困难在于,与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
这篇关于使用awk将列中的值替换为txt文件中的另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!