Home > OS >  Sed search replace a pattern in Shell script [duplicate]
Sed search replace a pattern in Shell script [duplicate]

Time:10-07

#!/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} 

current code: setenv workspace /path/a/b/c

needed : setenv workspace /path/updated which is $work_dir

result from script : setenv workspace $work_dir

CodePudding user response:

You can try this

#!/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}" 

CodePudding user response:

Try:

  • using double quotes (") in place of single
  • replace separator with a character that's not the slash / (I used :)
  • use -e option (not sure about this, but it works on my Mac)

in the sed command:

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

Explanation: by using a different delimiter than the slash in sed, the slash can be used as a literal character and so you can enter the path as it is without having to escape the slashes. Link: delimiter in sed substitution can be any other single character.

Alternatively, with slash escaping:

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

Related questions: 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

  • Related