Home > database >  BASH - replace with variable contain double quotes inside
BASH - replace with variable contain double quotes inside

Time:03-14

I have an text file, with line inside...

line: <version="AAA" email="...ANY..." file="BBB">

new desired line in text file to be: <version="AAA" email="NEW_TEXT" file="BBB">

I want to replace the ...ANY... expression with variable (replace entire line)

I have this script text-file script in #!/bin/bash, but I have problem when expanding double quotes in variables.

LINE_NUMBER="$(grep -nr 'email' *.txt | awk '{print $1}' | sed 's/[^0-9]*//g')"

VAR1="$(grep 'email' *.txt | cut -d '"' -f1-3)"

VAR2="$(grep 'email' *.txt | cut -d '"' -f5-)"

VAR3='NEW_TEXT'

NEW_LINE=$VAR1'"'$VAR3'"'$VAR2
new desired line in text file to be... <version="AAA" email="NEW_TEXT" file="BBB">

awk -i inplace 'NR=='"$LINE_NUMBER"'{sub(".*",'"'$NEW_LINE'"')},1' *.txt

but I get this new line:
<version="" email="NEW_TEXT" file="">

what do I do wrong?

How can I prevent expand duouble quotes inside variable? please better write me an working example, I had tried other topics, forums, posts....but I have no luck.

CodePudding user response:

You cas use sed :

VAR3='NEW_TEXT'
sed -i "s/email=\"[^\"]*\"/email=\"$VAR3\"/" myfile.xml

CodePudding user response:

Suggesting:

  var3="text space % special < chars"

Note var3 may not contain & which is special replacement meaning in sed

  sed -E 's|email="[^"]*"|email="'"${var3}"'"|' input.1.txt

Explanation

[^"]* : Match longest string not having " till next ".

  • Related