I have a text file where I'd like to add a string in the beginning of the line, however, it has special characters and sed complains about that.

The warning I get is:

sed: 1: "s/^/curl curliian.bxss ...": bad flag in substitute command: 'b'

So I tried to escape the dot:

dirnamer="$(dirname $1 | sed 's/\./\\./g')"

Which didn't work, so I tried to escape the b, which didn't work either. So yeah, this is what I do right now:

sed -i '' "s/^/curl $dirnamer/g" ~/desktop/download

But it seems there's alot of problems to do with with sed, because of special characters. What's a better method?

  • when sed complains about b being a bad flag its not talking about the one following that .. its talking about s/^/replace/gpb where gpb are substitution flags and b is not valid. but you can just do: sed "i\\n$b" - though you might lose any backslashes in $b if you dont double them up, and if $b contains newlines you'll need to backslash escape those, too. – mikeserv Dec 7 '15 at 12:46
  • I know, but I am was not using a b flag. – DisplayName Dec 7 '15 at 12:47
  • well, you were. somewhere in your variable is /b – mikeserv Dec 7 '15 at 12:47
  • @mikeserv That's correct, I should have edited the variable to escape that too. – DisplayName Dec 7 '15 at 12:49
  • Please show us your actual input and the sed command you used. We can't tell you what you need to escape if we don't know what you're doing. – terdon Dec 7 '15 at 12:55

This awk command works fine.

awk '{print "curl $dirnamer|" $0;}'

Or doing this to the variable before:

sed 's/\/b/\\b/g' | sed 's/\/t/\\t/g'
  • 1
    dont bother looking for [bt] - the problem is / in both cases. s/[\/]/\\&/g' is good enough for a substitution field of an s command with a / delimiter to handle any variable that doesnt contain a newline. – mikeserv Dec 7 '15 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.