duplicate of answer https://stackoverflow.com/a/61808364/10440128
#!/bin/sh
read -d '' input <<EOF
a
b
EOF
echo "replace yes:"
echo "$input" >input.txt
sed -i 's/a/x/ w /dev/stdout' input.txt
echo "replace no:"
echo "$input" >input.txt
sed -i 's/z/x/ w /dev/stdout' input.txt
output:
replace yes:
x
replace no:
so, to check if sed did replace something:
#!/bin/sh
read -d '' input <<EOF
a
b
EOF
echo "$input" >input.txt
if [ -z "$(sed -i 's/a/x/w /dev/stdout' input.txt)" ]
then echo "replace no" # -z = "zero string"
else echo "replace yes"
fi
echo "$input" >input.txt
if [ -n "$(sed -i 's/z/x/w /dev/stdout' input.txt)" ]
then echo "replace yes" # -n = "nonzero string"
else echo "replace no"
fi
output:
replace yes
replace no
limitation: can handle only one substitution. so this does not work:
sed -i 's,a,b, w /dev/stdout ; s,b,a, w /dev/stdout' input.txt
error:
sed: couldn't open file /dev/stdout ; s,b,a, w /dev/stdout: No such file or directory
(sed treats everything after w
as a file path)
workaround: use multiple sed calls
#!/bin/sh
read -d '' input <<EOF
a
b
EOF
echo "$input" >input.txt
if [ -n "$(
sed -i 's/a/x/w /dev/stdout' input.txt &&
sed -i 's/x/a/w /dev/stdout' input.txt
)" ]
then echo "replace yes"
else echo "replace no"
fi
sed
most certainly does have an exit status, it just doesn't do what you need here. If thesed
command fails, for example, if you try to run it on a file you don't have write access to or one that doesn't exist,sed
will exit with a non-0 exit status. The exit status just indicates whethersed
managed to do what you told it to do, andecho "foo.bar" | sed 's/pop.*$//'
was correctly executed. It deleted all lines withpop
. That there were no such lines is irrelevant, the command still worked.