Matt
Matt

Reputation: 49

Bash variable search and replace instead of sed

See Code Review

See Github Project

I need to parse out instances of +word+ line by line (replace +word+ with blank). I'm currently using the following (working) sed regex:

newLine=$(echo "$line" | sed "s/+[a-Z]\++//g")

This violates "SC2001" according to "ShellCheck" validation;

SC2001: See if you can use ${variable//search/replace} instead.

I've attempted several variations without success (The string "+word+" remains in the output):

newLine=$(line//+[a-Z]+/)
newLine=$(line/+[a-Z]+//)
newLine=$(line/+[a-Z]\++/)
newLine=${line//+[a-Z]+/}
and more..

I've heard that in some cases sed is necessary, but I would like to use Bash's built in find and replace if possible.

Upvotes: 2

Views: 3484

Answers (1)

choroba
choroba

Reputation: 242333

The substitution in parameter expansion doesn't use regular expressions, but patterns. To get closer to regular expressions, you can turn on extended patterns:

shopt -s extglob
new_line=${line//++([a-Z])+}

Upvotes: 4

Related Questions