Using sed in ksh script with condition
I'm using a sed command for replacing some words in text files. This command is embedded in a ksh script. I would like to reach that not everytime will every replacement rule of sed fire, only if some conditions are filled. E.g. depending on a value of a shell variable.
In other words I would like to write this script without the if statement, I would rather include the conditional expression 开发者_Python百科inside the sed. Is it possible?
REPLACE_A=TRUE
if [ "$REPLACE_A" = "TRUE" ]
then
cat myfile \
| sed 's/A/B/g;
's/C/D/g;
's/E/F/g;'
else
cat myfile \
| sed 's/C/D/g;
's/E/F/g;'
fi
The only solution that pops into my mind is to store the sed
command in a variable, like
# in your script
SEDCMD=""
# ...
SEDCMD="s/A/B/g;"
# later
SEDCMD="${SEDCMD}s/C/D/g;"
# ...
# finally
sed "$SEDCMD" FILE
But it still not the solution you want.
You can't do it with sed, but with awk. If you like to try, I suggest you have a look at this:
http://www.grymoire.com/Unix/Awk.html
精彩评论