【问题标题】:Replace string between two specific scripts in a file with shell script用 shell 脚本替换文件中两个特定脚本之间的字符串
【发布时间】:2018-07-08 00:07:46
【问题描述】:

我有一个文本文件info.txt,其中包含:

/* prog_dir=/path/to/some/directory; */
dir_1=/some/other/path/to/a/directory/first;
dir_2=/some/other/path/to/a/directory/secord;

在这里,我想替换这两对字符串之间存在的字符串,例如dir_1=/some/other/path/to/a/directory/; AND dir_2=/some/other/path/to/a/directory/;R03_0 用于所有行 info.txt 文件。

对于每一行,它都应该应用替换。

转换后,info.txt 文件应该是这样的:

/* prog_dir=/path/to/some/directory; */
dir_1=/some/other/path/to/a/directory/R03_0;
dir_2=/some/other/path/to/a/directory/R03_0;

试过这个:

sed '/^dir_1=/some\/other\/path\/to\/a\/directory\//,/^;/R03_0' /path/to/the/text/file/info.txt

如果我们可以将替换脚本R03_0 作为变量$rel_ver 传递给sed/awk 命令会更好。

有什么建议吗?

【问题讨论】:

  • 所有行的目录路径都一样吗?

标签: bash awk sed sh


【解决方案1】:

您可以使用 sed 执行以下操作:

pattern='\/some\/other\/path\/to\/a\/directory'
str='R03_0'
sed "s/${pattern}\/.*;/${pattern}\/${str};/g" info.txt

输出:

/* prog_dir=/path/to/some/directory; */
dir_1=/some/other/path/to/a/directory/R03_0;
dir_2=/some/other/path/to/a/directory/R03_0;

这会将所有/some/other/path/to/a/directory/...; 替换为您想要的模式,即/some/other/path/to/a/directory/R03_0;

【讨论】:

    【解决方案2】:

    您可以使用组捕获来实现此目的:

    sed -re 's#^(/some/other/path/to/a/directory/).*;#\1R03_0;#g' info.txt
    

    这将“保存”大括号中匹配的模式,并将其放回\1

    【讨论】:

      【解决方案3】:

      因为所有行都以; 结尾:

      str='R03_3';
      sed -e "s/\(^.*\/\).*;$/\1${str};/" info.txt
      
      • \(^.*\/\) - 捕获匹配行首、任何字符和正斜杠的组
      • .+;$ - 至少一个字符后跟; 在行尾

      • \1${str}; - 替换为捕获组和变量str中定义的文本

      注意这不会改变文件,重定向输出或使用-i选项替换原地。

      【讨论】:

        猜你喜欢
        • 2018-05-03
        • 1970-01-01
        • 2014-11-24
        • 2017-11-17
        • 2021-03-06
        • 2012-11-05
        • 1970-01-01
        • 2020-03-10
        • 2016-08-25
        相关资源
        最近更新 更多