Use tr
instead:
tr -d "$OPTARG"
will delete all characters in OPTARG.
Or if you insist on using sed, use character sets:
sed "s/[$OPTARG]//g"
Frage
I'm trying to create a script that can use a command such as
script -c abcd test.txt
and it will get rid of any characters a
or b
or c
or d
inside test.txt.
This is the code I have so far:
while getopts ":c:" opt; do
case $opt in
c)
sed 's/'$OPTARG'//g'
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
But this only gets rid of "abcd" inside my file, not a or b or c or d, not acdb etc. How do I make SED read the OPTARG as seperate characters?
Lösung
Use tr
instead:
tr -d "$OPTARG"
will delete all characters in OPTARG.
Or if you insist on using sed, use character sets:
sed "s/[$OPTARG]//g"
Andere Tipps
You need to group the characters together so that they're a character class.
ross@ross-laptop ~> cat foo
agkdjbdefghijglkthdn
ross@ross-laptop ~> sed 's/[abcd]//g' foo
gkjefghijglkthn
Hope that helps.