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