4

in a bash script file, I have set one variable like this:

    current_path=`pwd`
    sed -i "1s/.*/working_path='$current_path';/" file1.sh

I want to run this script to replace the first line of file1.sh into working_path='$current_path';, but the current_path has the / and in the sed command, the / is predefined in sed replace pattern. And I have tried this:

    current_path1="${current_path/\//\\\/}"

the above line, I want to replace the / in variable current_path into \/, then input the current_path1 into the sed command, but also has an error.

Could you give me some advice, please? Thanks.

mining
  • 3,557
  • 5
  • 39
  • 66
  • possible duplicate of [sed scripting - environment variable substitution](http://stackoverflow.com/questions/584894/sed-scripting-environment-variable-substitution) – tripleee Nov 24 '14 at 06:30
  • @tripleee, thank you. That post is very helpful. Maybe I couldn't find that post at that time I faced the question. Or I used different keywords so that the search engine didn't return the index of that post. Thus, I made a new post here. – mining Nov 24 '14 at 07:18

3 Answers3

7

Try this.

sed -i -e "1s@.*@working_path='$current_path';@" file1.sh

Use @ instead of / in the substitute command.

Rafa Viotti
  • 9,998
  • 4
  • 42
  • 62
2

You can use different delimiters for the s/// command:

current_path=`pwd`
sed -i "1s|.*|working_path='$current_path';|" file1.sh

But you're not really searching and replacing here,, you want to insert the new line and delete the old line:

current_path=`pwd`
sed -i -e "1i\working_path='$current_path)';" -e 1d file1.sh

Are you really changing the first line of a .sh file? Are you deleting the she-bang line?

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Yes, sir, when I run this `sed -i "1s/.*/working_path='\/home\/user\/Desktop';/" file1.sh` in terminal, it worked, but it will replace the `#/bin/bash` into `working_path='/home/user/Desktop;'` – mining Oct 29 '13 at 01:32
  • My search and replace fails, any idea why? `sed -i "s|\`"$foo"|\`"$bar"/g" "$file"`. The error is: `command substitution: line 28: syntax error: unexpected end of file; sed: -e expression #1, char 22: unterminated \`s' command` – Dennis Feb 26 '14 at 17:01
  • are those backticks supposed to be there? – glenn jackman Feb 26 '14 at 17:05
0

Please add a '/' to the beginning of pattern string. It replaces all matches of pattern with string.

 current_path1="${current_path//\//\\\/}"
Jun Kawai
  • 21
  • 2