1

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.

Scripter
  • 23
  • 4
  • 2
    To edit xml files use xml aware programs. Like xmllint, xmlstarlet. `How can I prevent expand duouble quotes inside variable?` https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – KamilCuk Mar 13 '22 at 06:43
  • You should use sed. – Yuji Mar 13 '22 at 07:03

2 Answers2

0

You cas use sed :

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

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 ".

Dudi Boy
  • 4,551
  • 1
  • 15
  • 30