Awk将不会替换所有列

问题描述:

我试图用awk like this替换某个文件的某一列。我可以得到它的工作使用Awk将不会替换所有列

awk '{ sub(/4$/, "Q", $6) }1' temp2.txt 

然而在列6使用

awk '{ sub(/r$/, "Q", $3) }1' temp2.txt 

或者“4”来代替“R”,在第3栏,我不能做的“T替换“第4栏

文件的内容是

cat temp2.txt 

224245 CO2_Cells_50_V_-100_P_760 r 2016-08-18T13:35:12.337 [email protected] 4 
224256 CO2_Cells_100_V_-200_P_760 r 2016-08-18T13:35:15.408 [email protected] 4 
224261 CO2_Cells_100_V_-250_P_760 r 2016-08-18T13:35:16.425 [email protected] 4 
224262 CO2_Cells_150_V_-250_P_760 r 2016-08-18T13:35:16.426 [email protected] 4 
224264 CO2_Cells_250_V_-250_P_760 r 2016-08-18T13:35:17.438 [email protected] 4 
224266 CO2_Cells_100_V_-300_P_760 r 2016-08-18T13:35:17.440 [email protected] 4 
224267 CO2_Cells_150_V_-300_P_760 r 2016-08-18T13:35:17.442 [email protected] 4 
224268 CO2_Cells_200_V_-300_P_760 r 2016-08-18T13:35:17.443 [email protected] 4 
224269 CO2_Cells_250_V_-300_P_760 r 2016-08-18T13:35:18.460 [email protected] 4 
224271 CO2_Cells_100_V_-350_P_760 r 2016-08-18T13:35:18.463 [email protected] 4 
224272 CO2_Cells_150_V_-350_P_760 r 2016-08-18T13:35:18.464 [email protected] 4 
224273 CO2_Cells_200_V_-350_P_760 r 2016-08-18T13:35:18.466 [email protected] 4 
224274 CO2_Cells_250_V_-350_P_760 r 2016-08-18T13:35:19.539 [email protected] 4 
224277 CO2_Cells_150_V_-400_P_760 r 2016-08-18T13:35:19.543 [email protected] 4 
224278 CO2_Cells_200_V_-400_P_760 r 2016-08-18T13:35:19.545 [email protected] 4 
224279 CO2_Cells_250_V_-400_P_760 r 2016-08-18T13:35:20.649 [email protected] 4 
224282 CO2_Cells_150_V_-450_P_760 r 2016-08-18T13:35:20.653 [email protected] 4 
224283 CO2_Cells_200_V_-450_P_760 r 2016-08-18T13:35:20.654 [email protected] 4 
224287 CO2_Cells_150_V_-500_P_760 r 2016-08-18T13:35:21.718 [email protected] 4 
224288 CO2_Cells_200_V_-500_P_760 r 2016-08-18T13:35:21.720 [email protected] 4 
224289 CO2_Cells_250_V_-500_P_760 r 2016-08-18T13:35:21.721 [email protected] 4 
224522 CO2_Cells_250_V_-450_P_760 r 2016-08-18T14:54:09.720 [email protected] 4 
224699 CO2_Cells_50_V_-150_P_760 r 2016-08-18T18:04:18.900 [email protected] 4 

正则表达式中的$与字符串的末尾相匹配 - 即它只会替换列末尾的文本。 如果要替换列中任何位置的文本,请使用sub(/T/, "Q", $4),但它只会替换第一个匹配的文本。

要更换所有“T的一列中,使用的gsub代替sub

尝试:awk '{ sub(/[[T]/, "XYZ", $4) }1'

子第一参数/[[T]/可以包含任何需要替换的字符 - 对于您的情况,然后T

+0

没有'/ [T] /'经过短短'/ T /'的好处。 –

+0

同意,如果需要更换多个char,则更多的是一个示例。 –