简体   繁体   中英

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.

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])+}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM