【问题标题】:Replace text before last slash, between quotes and on certain line替换最后一个斜杠之前、引号之间和特定行上的文本
【发布时间】:2020-12-07 18:50:57
【问题描述】:

如果我有一个包含多行的文本文件:

source = "/directory/something/module1"
sometext sometext
source = "/directory/something/module2"
sometext sometext
source = "/directory/something/module3"

所以对于每行有source = "/some directory/some module"

我想替换最后一个正斜杠之前的数据。所以我会以这样的方式结束:

source = "./module/module1"
sometext sometext
source = "./module/module2"
sometext sometext
source = "./module/module3"

需要保留模块名称,并替换它们的包含目录。

【问题讨论】:

  • 请以代码的形式添加您的努力,这在 SO 上受到强烈鼓励。
  • sed -e '/source/s@".*/@"./module/@' file
  • 谢谢@kvantour,虽然我不明白为什么??
  • philthy - @karakfas 建议适用于发布的示例输入,但不适用于其他输入。例如,尝试用my "problem" source is that N/0 is invalid 替换任何行上的sometext。为给定的示例输入生成预期输出的脚本是确定解决方案的起点,而不是终点,匹配您想要的文本总是微不足道的,但不匹配您不想要的文本要困难得多。
  • 在决定它是否有效之前了解潜在的解决方案很重要,并且努力创建示例输入/输出来测试不仅仅是您的晴天案例,尤其是涵盖您的案例可以想象可能会导致您不想匹配但看起来与您匹配的匹配。

标签: awk sed


【解决方案1】:

您能否尝试使用所示示例进行以下、编写和测试。

awk '/^source.*module[0-9]+$/{sub(/\/.*\//,"./module/")} 1' Input_file

说明:为上述添加详细说明。

awk '                         ##Starting awk program from here.
/^source.*module[0-9]+$/{     ##Checking condition if line starts from source and ends with module digits then do following.
  sub(/\/.*\//,"./module/")   ##Substituting from slash to last occurrence of s;ash with ./module/ here.
}
1                             ##1 will print line.
' Input_file                  ##Mentioning Input_file name here.

【讨论】:

    【解决方案2】:

    您可以将此sed 与 2 个捕获的组一起使用:

    sed -E 's~(source *= *").*(/[^/]+")~\1./module\2~' file
    
    source = "./module/module1"
    sometext sometext
    source = "./module/module2"
    sometext sometext
    source = "./module/module3"
    

    要将更改内联保存到同一文件,请使用:

    sed -E -i.bak 's~(source *= *").*(/[^/]+")~\1./module\2~' file
    

    【讨论】:

      【解决方案3】:

      您可以为此使用 awk:

      awk -F\/ '$(NF) ~ /module/ { $0="source = \"./module/"$(NF) }1' file
      

      将字段分隔符设置为/,然后搜索最后一个字段包含模块的任何条目。对于这些条目,将 $0(行)更改为重新格式化的行,并合并最后一个字段。用简写 1 打印所有行。

      【讨论】:

        【解决方案4】:

        也许这个简单的awk 可以帮助使用gsub() 功能:

        awk '/"\/directory\/something\/module1"/ gsub(/\/directory\/something/,"./module")1' file
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-14
          • 1970-01-01
          • 1970-01-01
          • 2019-04-12
          • 2021-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多