找到一个模式并替换

时间:2018-05-29 02:53:28

标签: linux bash shell

这是我文件的输入。

Number : 123
PID    : IIT/123/Dakota

预期输出为:

Number : 111
PID    : IIT/111/Dakota

我想将123替换为111.为了解决这个问题,我尝试了以下内容:

awk '/Number/{$NF=111} 1' log.txt
awk -F '[/]' '/PID/{$2="123"} 1' log.txt

2 个答案:

答案 0 :(得分:2)

使用sed这么简单吗?

将更改打印到屏幕上(使用此测试):

  sed -e 's:123:111:g' f2.txt 

更新文件(使用此文件):

  sed -i 's:123:111:g' f2.txt 

示例:

$ sed -i 's:123:111:g' f2.txt 
$ cat f2.txt 
Number : 111
PID    : IIT/111/Dakota

答案 1 :(得分:1)

EDIT2: 或者您希望用123替换每一行的111而不检查您在{{1}中尝试的任何条件然后简单地做:

awk

如果一行中出现多次awk '{sub(/123/,"111")} 1' Input_file ,请将sub更改为gsub

上述代码说明:

123

编辑: 如果您的输出中还需要awk -v new_value="111" ' ##Creating an awk variable named new_value where OP could keep its new value which OP needs to be there in line. /^Number/ { $NF=new_value } ##Checking if a line starts from Number string and then setting last field value to new_value variable here. /^PID/ { num=split($NF,array,"/"); ##Checking if a line starts from PID then creating an array named array whose delimiter it / from last field value array[2]=new_value; ##Setting second item of array to variable new_value here. for(i=1;i<=num;i++){ val=val?val "/" array[i]:array[i] }; ##Starting a loop from 1 to till length of array and creating variable val to re-create last field of current line. $NF=val; ##Setting last field value to variable val here. val="" ##Nullifying variable val here. } 1' Input_file ##Mentioning 1 to print the line and mentioning Input_file name here too. ,请使用以下/

awk

关注awk -v new_value="111" ' /^Number/ { $NF=new_value } /^PID/ { num=split($NF,array,"/"); array[2]=new_value; for(i=1;i<=num;i++){ val=val?val "/" array[i]:array[i] }; $NF=val; val="" } 1' Input_file 可能会对您有所帮助。(在我将示例代码应用到您的示例后,您的示例输入会稍微改变一下,所以现在相应地编辑我的代码)

awk

如果您想将更改保存到Input_file本身,请在上面的代码中添加awk -F"[ /]" -v new_value="111" '/^Number/{$NF=new_value} /^PID/{$(NF-1)=new_value}1' Input_file

<强> 说明:

> temp_file  &7 mv temp_file  Input_file