1

This is my current code. I am trying to replace a filename string in the file with another filename. But I am currently getting the error

"sed: 1: "s/directory = "[A-Za-z0 ...": bad flag in substitute command: 'U'"

What is wrong with this code?

function restart_existing ()
{
    old="directory = \"[A-Za-z0-9\/]\""
    new="directory = \"$1\""
    sed -i '' "s/$old/$new/" "$HOME/angelpretendconfig" 
}


restart_existing "$HOME/blahblahblah/shoot/blah"

EDIT: Thanks! I've adopted your advice, and adapted the code.

function restart_existing ()
{
    old="directory = \"*\""
    printf -v new 'directory = "%s"' "$1"
    sed -i '' "s;$old;$new;" "$HOME/angelpretendconfig" 
}

restart_existing "Query"

But now the line in question goes from

directory = "/home/jamie/bump/server"
directory = "Query"/home/jamie/bump/server"

Why does this occur?

Kenneth Tiong
  • 31
  • 1
  • 3

2 Answers2

7

Don't use forward slashes in sed when what you're replacing contains forward slashes:

$ sed 's;foo/bar;baz/wuz;' <<< "where is the foo/bar?"
where is the baz/wuz?

Also, sometimes it's more readable to avoid manually escaping quotes:

function restart_existing ()
{
    old='directory = "[A-Za-z0-9\/]"'
    printf -v new 'directory = "%s"' "$1"
    sed -i '' "s;$old;$new;" "$HOME/angelpretendconfig" 
}

restart_existing "$HOME/blahblahblah/shoot/blah"
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • Thanks! I've adopted your advice, and adapted the code. function restart_existing () { old="directory = \"*\"" printf -v new 'directory = "%s"' "$1" sed -i '' "s;$old;$new;" "$HOME/angelpretendconfig" } restart_existing "Query" But now the line goes from directory = "/home/jamie/bump/server" directory = "Query"/home/jamie/bump/server" Why does this occur? – Kenneth Tiong Jul 18 '12 at 22:35
  • @KennethTiong because `sed 's;directory = \"*\";something;'` means *Replace `directory =` followed by any number of double-quotes (plus one) with `something`* – kojiro Jul 18 '12 at 22:43
1

$1 contains something, which is parsed as a special command to sed, in this case probably a / which marks the end of the replacement string, followed by some other characters.

You have to escape the replacement string first: Escape a string for a sed replace pattern.

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176