I am using sed
command to change
to
in an xml file. Now if I use
sed 's/true/false/g' file.xml > file.xml
it completely erases the content of my file. While using >>
instead of >
, it appends output at the end like it is expected to do.
- How to achieve what I want to do?
- Why is
>
behaving so weirdly? - What i actually want to do is change
totrue
iffalse
is present and vice versa iftrue
is present in file. Is there some command that can do it or do I need to write a script withfalse if-else
like my original plan?
Answer
The behavior of >
is explained in this Unix & Linux SE answer. The example there is cat test.txt > test.txt
and the explanation is:
The first thing that happens is bash opens
test.txt
, which truncates the file. It is now empty, beforecat
is executed withtest.txt
as an argument.
Your sed '…' file.xml > file.xml
triggers the same behavior.
Quite straightforward solution with a single sed
:
sed -i 's/true/DUMMY/g
s/false/true/g
s/DUMMY/false/g' file.xml
The -i
option solves your problem with the file being truncated. The command turns
into
and vice versa. Note you cannot use just
s/true/false/g;s/false/true/g
because the second part cannot tell if any false
is the original false
or the original true
just turned into false
. This causes every matching true
or false
end up as true
. For this reason I used the temporary DUMMY
replacement. Maybe there is a better way to do it, I don't know it yet.
The only condition is the string
cannot appear in the original file. If it may appear, use another dummy string which doesn't appear for sure.
No comments:
Post a Comment