1

When I use a normal value like a=10

I am able to get the sed find/replace working

  sed -e "s/xxx/$a/g" a.txt

But when I try to use a variable like a=http://xyz.com

sed -e "s/xxx/$a/g" a.txt is not working...

Its throwing unknown option error which I assume is due to the escape characters that are present over the variable

Kent
  • 189,393
  • 32
  • 233
  • 301
user1386776
  • 395
  • 3
  • 8
  • 13

2 Answers2

5

try this:

sed -e "s@xxx@$a@g" a.txt 
Kent
  • 189,393
  • 32
  • 233
  • 301
  • ...until your URL contains an "@" symbol :-). – Ed Morton Mar 25 '13 at 13:47
  • @EdMorton ^_^ ur right!! ...hum. maybe `sed -e "s>xxx>$a>g" a.txt` ? – Kent Mar 25 '13 at 13:52
  • I don't think there's any guarantee that a URL doesn't contain a ">" but I'm no expert on URLs. Personally, I just wouldn't use sed on a URL or a file name (which can also contain almost any character) - that way I don't need to worry about it :-). Of course if you have complete control over the names and can guarantee what characters they do/don't contain then that's a different story. – Ed Morton Mar 25 '13 at 13:59
  • 1
    @EdMorton it seems that `<,>` are invalid chars for url. http://stackoverflow.com/questions/7109143/what-characters-are-valid-in-a-url but you are right if there is a solution which doesn't require those kind of concerns..., we shall go that way. – Kent Mar 25 '13 at 14:07
  • @Kent it would certainly make sense if < and > couldn't be part of a URL so I think you're probably right and those are safe delimiters for sed on URLs. Not sure if you intended "," to be part of the safe set, but to be clear it's not. Thanks! – Ed Morton Mar 25 '13 at 14:12
  • Surprisingly, at least in the version of sed I have, spaces are legal delimiters for s. Since a URL shouldn't contain a literal space, this should be safe enough: `sed -e 's xxx $a '` An alternative is to use a tool that has balanced delimiters - in Perl, for example, `s{xxx}{$a}` should work. – William Mar 25 '13 at 14:28
  • URLs can contain literal spaces, unfortunately. – Ed Morton Mar 25 '13 at 14:39
  • To be safe I usually use a non-printable char as the `s` command separator. For example: `SEP=$'\033'; sed -e "s${SEP}foo${SEP}bar${SEP}" ...` – pynexj Mar 25 '13 at 15:02
4

With awk your string can contain ANY character, including /, @, newline, whatever:

$ a="http://xyz.com"
$ echo "<xxx>" | awk -v a="$a" '{gsub(/xxx/,a)}1
<http://xyz.com>
Ed Morton
  • 188,023
  • 17
  • 78
  • 185