【问题标题】:Sed search replace a pattern in Shell script [duplicate]Sed搜索替换Shell脚本中的模式[重复]
【发布时间】:2021-11-27 06:10:51
【问题描述】:
#!/bin/bash 
work_dir=`pwd`

syn_file="$work_dir/di/aon_lint/dc/run_syn"

sed -i 's/setenv workspace.*/setenv workspace $work_dir/g' ${syn_file} 

当前代码:setenv workspace /path/a/b/c

需要:setenv workspace /path/updated,即$work_dir

脚本结果:setenv workspace $work_dir

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    试试:

    • 使用双引号 (") 代替单引号
    • 用不是斜线/的字符替换分隔符(我用:
    • 使用-e 选项(不确定,但它适用于我的Mac)

    在 sed 命令中:

    sed -i -e "s:setenv workspace.*:setenv workspace $work_dir:g" ${syn_file}
    

    解释:通过使用与sed 中的斜杠不同的分隔符,斜杠可以用作文字字符,因此您可以按原样输入路径,而无需转义斜杠。链接:delimiter in sed substitution can be any other single character.

    或者,使用斜线转义:

    escaped_work_dir=$(echo "$work_dir" | sed 's%/%\\/%g')
    sed -i -e "s/setenv workspace.*/setenv workspace $escaped_work_dir/g" ${syn_file}
    

    相关问题:How to use sed command to replace folder path names in linux?How to replace a path with another path in sed?How to pass a variable containing slashes to sed

    【讨论】:

      【解决方案2】:

      你可以试试这个

      #!/usr/bin/env bash
      
      work_dir=$(pwd)
      syn_file="$work_dir/di/aon_lint/dc/run_syn"
      
      sed -i "s|\(setenv workspace \).*|\1$work_dir|g" "${syn_file}" 
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2014-06-08
      • 2018-11-16
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多