0

I have a replacement string which is captured in a parameter replace_str. The below command with sed for replacement gives bad substitution error :

sed 's/search_str/$replace_str/' 

where replace_str has the value with backslash eg: 01/2020

Tried few options like using \, within double quotes etc .But it did not help . Please let me know if you need more information.

Appreciate your time and help.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
abhiram
  • 3
  • 1
  • 2
    This is because when `$replace_str` is interpreted, `sed` command has many slahes. Try to use another separator: `sed "s_search_str_$replace_str_"` Also note you need double quotes to have the var expanded. – fedorqui May 06 '14 at 14:42
  • @fedorqui underscore as a seperator? – Avinash Raj May 06 '14 at 14:45
  • 1
    @AvinashRaj yes, you can define it, as well as `|` or others. Just check it out with a very basic `echo "hello" | sed 's_hello_bye_'`. Even `sed 's?hello?bye?'` works. – fedorqui May 06 '14 at 14:48
  • prepare the string $replace_str by escaping special char (with a previous sed in a temporary variable). if there is only digit and /, you could use another s/// separator like s### or s::: – NeronLeVelu May 06 '14 at 14:54
  • @fedorqui : I tried with double quotes too . it is a date parameter so i have to use the forward slash as the preferred seperator . Also is there any turn-around for back slash ? even tried it this way : sed 's/\*\*\*/.`echo $replace_str|sed 's/^\(.\{2\}\)/\1\//'`/' where the command gets the date in mm/yyyy format . Please help !! – abhiram May 06 '14 at 14:55
  • @neronleVelu , actually was trying to do get . i can bring the value correctly as mm/yyyy format into a string but unable to send it to replace another string in a file using the sed . – abhiram May 06 '14 at 15:00

2 Answers2

1

As I cannot make it clear in comments, I post as an answer:

$ var="01/2020"

Using sed "s/... it fails:

$ echo "hello you" | sed "s/hello/$var/"
sed: -e expression #1, char 16: unknown option to `s'

This is because it gets converted into something with so many slashes /: $ echo "hello you" | sed "s/hello/01/2020/"

Instead, use another separator, for example ? or |:

$ echo "hello you" | sed "s?hello?$var?"
01/2020 you

$ echo "hello you" | sed "s|hello|$var|"
01/2020 you
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0
replace_str_esc="$( echo "${replace_str}" | sed 's|[][\\&]|\&|g' )"
sed "s/{search_str}/${replace_str_esc}/" YourFile

more generique on replaced string (for a single /, it's faster to use directly sed with another separator of patterne substitution.

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43