0

Ubuntu 16.04

I have some pretty large file so modifying it by hand is not possible. I'd like to change all occurences of

<tag1>true</tag1>

to

<tag1>false</tag1>
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

3 Answers3

5

You can use

sed -e 's|<tag1>false</tag1>|<tag1>true</tag1>|g' -i file

although I recommend doing the edit to a copy of the file,

sed -e 's|<tag1>false</tag1>|<tag1>true</tag1>|g' file > newfile

and using less to check if the new contents are acceptable; i.e.

less newfile

Edited: Note the g modifier at the end of the pattern. It is necessary, if there can be more than one match on a line. When g is present, it means all matches on a line are replaced. Furthermore, instead of complete tags, you could consider just

sed -e 's|>false<|>true<|g' file > newfile

or perhaps

sed -e 's|>[Ff]alse<|>true<|g' file > newfile

which changes both >false< and >False< to >true<.

You can use diff to compare the two files, after using one of the commands above. One option is

diff --side-by-side file newfile | less

but it does not really work if the lines are very long. The "unified diff" format is commonly used,

diff -u file newfile | less

where lines beginning with - are from file, lines beginning with + from newfile, and lines beginning with a space are common to both.

2

If you want to replace only the exact occurrences of

<tag1>true</tag1>

to

<tag1>false</tag1>

you can use

sed -r 's@<(tag1)>true</\1>@<\1>false</\1>@g' infile >outfile

or

sed -ri 's@<(tag1)>true</\1>@<\1>false</\1>@g' file

if you do not want to write the changed data to a new file.

Abrixas2
  • 878
0

It is easy to achieve with sed command.
Just run:

sed 's/true/false/' file > newfile
micjan
  • 73
  • 2
    this might incorrectly match lines that had "true" text without the surrounding tag text. – Jeff Schaller Nov 08 '16 at 18:41
  • 1
    Plus, you want the g at the end, so that lines with more than one match have all the matches edited. I guess `s|>true<|>false<|g' would be a good middle ground between no tags at all, and replacing only exact matches with complete tags? – Nominal Animal Nov 08 '16 at 18:55