查找 - 替换 - 使用shell脚本更新字符串

时间:2014-04-22 08:58:33

标签: shell unix replace awk grep

我有一个包含

之类的行的文件
https://abcdefgh.com/123/pqrst/456/xyz.html

所以我想在该文件中搜索此行并将xyz.html替换为mno.html

将shell脚本中的mno.html作为输入。

怎么做?

3 个答案:

答案 0 :(得分:2)

$ awk 'BEGIN{FS=OFS="/"} index($0,"https://abcdefgh.com/123/pqrst/456/xyz.html"){$NF="mno.html"} 1' file
https://abcdefgh.com/123/pqrst/456/mno.html

或两个值是否已存储在shell变量中:

$ old="https://abcdefgh.com/123/pqrst/456/xyz.html"
$ new="mno.html"
$ awk -v old="$old" -v new="$new" 'BEGIN{FS=OFS="/"} index($0,old){$NF=new} 1' file
https://abcdefgh.com/123/pqrst/456/mno.html

答案 1 :(得分:0)

您可以使用此sed

sed '/https:\/\/abcdefgh.com\/123\/pqrst\/456\/xyz.html/s#\(.*\/\)\(.*\)#\1mno.html#g' yourfile

答案 2 :(得分:0)

使用awk如果该行与示例完全相同,我的意思是如果之前或之后没有其他字符

awk '{print gensub(/^(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html$/,"\\1mno.html","g")}' input.txt

否则:

awk '{print gensub(/(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html/,"\\1mno.html","g")}' input.txt