modzello86
modzello86

Reputation: 433

Filter input to remove certain characters/strings

I have quick question about text parsing, for example:

INPUT="a b c d e f g"
PATTERN="a e g"

INPUT variable should be modified so that PATTERN characters should be removed, so in this example:

OUTPUT="b c d f"

I've tried to use

tr -d $x
in a for loop counting by 'PATTERN' but I don't know how to pass output for the next loop iteration.

edit: How if a INPUT and PATTERN variables contain strings instead of single characters???

Upvotes: 2

Views: 6453

Answers (2)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

Pure Bash using parameter substitution:

INPUT="a b c d e f g"
PATTERN="a e g"

for p in $PATTERN; do
  INPUT=${INPUT/ $p/}
  INPUT=${INPUT/$p /}
done
echo  "'$INPUT'"

Result:

'b c d f'

Upvotes: 2

choroba
choroba

Reputation: 242038

Where does $x come from? Anyway, you were close:

tr -d "$PATTERN" <<< $INPUT

To assign the result to a variable, just use

OUTPUT=$(tr -d "$PATTERN" <<< $INPUT)

Just note that spaces will be removed, too, because they are part of the $PATTERN.

Upvotes: 3

Related Questions