1

Let's say I have this text: My name is #1#!.

I want to replace the #1# with something that depends on the contents between the #, like:

if [ $thing_between_hash -eq 1 ]; then
  subs=John
else
  subs=Mary
fi

Then the output would be:

My name is John!

Can I do it with a single sed substitution? How?

  • 1
    If your substitution needs get much more complicated, see templating solutions, such as [mustache](https://unix.stackexchange.com/a/350743/117549) – Jeff Schaller Dec 30 '17 at 15:25

3 Answers3

5

With a sed that supports -r:

sed -r -e 's/#1#/John/g; s/#[^#]+#/Mary/g' <<< 'My name is #1#, not #5#!'

otherwise:

sed    -e 's/#1#/John/g; s/#[^#][^#]*#/Mary/g' <<< 'My name is #1#, not #5#!'
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
  • 3
    Instead of `-r` suggest using equivalent `-E` since, per the man page, "the -E option has been supported for years by GNU sed, and is now included in POSIX." – B Layer Dec 30 '17 at 15:46
  • I failed to find `-E` in http://pubs.opengroup.org/onlinepubs/9699919799/ but will look again when I get back to a computer. Do you have a more direct reference for it? – Jeff Schaller Dec 30 '17 at 17:03
  • Breadcrumb: https://unix.stackexchange.com/q/310446/117549 – Jeff Schaller Dec 30 '17 at 17:12
  • 1
    You won't find it in the current documentation. It will be included in the [next posix issue](http://austingroupbugs.net/view.php?id=528) – don_crissti Dec 30 '17 at 17:33
1

With bash:

something='My name is #1#!'
subs="John"

mod="${something/\#1\#/$subs}"

echo "$mod"

Output:

My name is John!
Cyrus
  • 12,059
  • 3
  • 29
  • 53
0

can do so as :

 [root@h2g2w ~]# subs=john
 [root@h2g2w ~]# echo may name is 1 | sed
> 's/1/'$subs'/' 
  may name is john 
 [root@h2g2w ~]#
francois P
  • 1,219
  • 11
  • 27
  • 1
    What you've written is syntactically invalid. If it has been mangled by your formatting, please fix that. And some explanation of what you're doing and how it can help the OP would make this a useful answer. – roaima Dec 30 '17 at 16:41
  • It also doesn’t anchor the replacements inside hash marks. – Jeff Schaller Dec 30 '17 at 17:21
  • echo "may name is #1#" | sed 's/#1#/'$subs'/' may name is john this just absolutly works it is the one way to do so & proved as a really done thing...copy/pasting of solution tested :) – francois P Dec 30 '17 at 17:58
  • But what about “My name is #1#, and I’m #1!” – Jeff Schaller Dec 30 '17 at 18:16
  • this is not the user question , and in this cas this just works without confusion until I use the one good #1# mark that can't be confused with #1! so sed exit the good sentance with one & only one subsitution – francois P Dec 30 '17 at 18:18
  • It is, actually: `I want to replace the #1#` ... – Jeff Schaller Dec 30 '17 at 22:00