0

Update

Thanks @steeldriver for the answerd, the problem doesn't the double quote is the / only i needeed remplace for |

Currently I have some problems with the sed command, I try to replace a string inside a file, the problem is the replace contains a double quote.

The variable contain the value of a file: the variable text have this value

<string name="app_mod_app_crowdin_1">crowdin one es</string>

The problem is when execute the command sed

  sed -i .bak -e "Ns/.*/$text/" results.txt

error

sed: 1: "1s/.*/<string name="app ...": bad flag in substitute command: 's'

2 Answers2

0
foo='"hello world"'
echo $foo
"hello world"
echo '"hello world"' | sed 's/'"$foo"'/bye hell/'
bye hell
Jiri B
  • 541
  • 1
  • 7
  • 16
  • The quality of this answer could be improved by explaining the change (single quotes) instead of just demonstrating it. Also take note of https://unix.stackexchange.com/questions/32907/what-characters-do-i-need-to-escape-when-using-sed-in-a-sh-script – Jeff Schaller Mar 23 '21 at 18:47
0

Don't inject user-supplied data into a sed script. It's more trouble than it's worth and could in many cases also be a security hole (especially with GNU sed which allows for arbitrary code execution). Remember that injecting $text into the replacement part of a s/// command actually modifies your sed script using whatever string $text is.

If you just need to change the first line to some fixed string, use awk instead:

cp results.txt results.txt.bak &&
awk -v value="$text" 'NR == 1 { $0 = value }; 1' results.txt.bak >results.txt

Testing:

$ text='<string name="app_mod_app_crowdin_1">crowdin one es</string>'
$ cat results.txt
line 1
line 2
line 3
$ cp results.txt results.txt.bak && awk -v value="$text" 'NR == 1 { $0 = value }; 1' results.txt.bak >results.txt
$ cat results.txt
<string name="app_mod_app_crowdin_1">crowdin one es</string>
line 2
line 3

The awk code simply replaces the current line with the given text if NR == 1, i.e. if this is the first line of the file. The trailing 1 causes all lines to be printed, whether modified or not.

Kusalananda
  • 333,661