0

What I want to do is edit an xml file, and replace something that is inside one of the tags. This is my script:

while read line; do
if [[ "$line" == *"<Valuec=\"0\">"* ]]
then 
~/bin/nn4 Decrypt1 "$line" | sed 's/^/\<Valuec=\"0\"\>/g;s/$/\<\/Valuec\>/g'
fi
done <"$1"

nn4 removes the tags, decrypts the contents and the sed command puts the tags back.

Here is the input

<string>
    <Id>1</Id>
    <file>file.txt</file>
    <Valuec="0">982498as9adhfsdf</Valuec>
</string>
<string>
    <Id>2</Id>
    <strStringCaption>file2.txt</strStringCaption>
    <Valuec="0">2389aHASDasd</Valuec>
</string>

However, this, ofcourse, only outputs the lines that are edited. It looks something like this:

<Valuec="0">decryptedstring</Valuec>
<Valuec="0">decryptedstring2</Valuec>

However, I want it to look like this:

<string>
    <Id>1</Id>
    <file>file.txt</file>
    <Valuec="0">decryptedstring</Valuec>
</string>
<string>
    <Id>2</Id>
    <strStringCaption>file2.txt</strStringCaption>
    <Valuec="0">decryptedstring2</Valuec>
</string>
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
DisplayName
  • 11,688

1 Answers1

2

Just add an else condition to your body of while loop:

while IFS= read -r line; do
if [[ "$line" == *"<Valuec=\"0\">"* ]]
then 
  ~/bin/nn4 Decrypt1 "$line" | sed 's/^/\<Valuec=\"0\"\>/g;s/$/\<\/Valuec\>/g'
else
  printf '%s\n' "$line"
fi
done <"$1"

Note the use of IFS= read -r to completely read a line.

Anyway, you should consider to use other the tools for this task. Using while loop in shell script is considered bad practice.

cuonglm
  • 153,898