Bash变量搜索和替换而不是sed。

时间:2022-06-01 19:17:39

See Code Review

看到代码评审

See Github Project

看到Github项目

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

我需要逐行解析+word+实例(用空格替换+word+)。我目前正在使用以下(工作)sed regex:

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

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

根据“ShellCheck”验证,这违反了“SC2001”;

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

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

我尝试过几种变体,但没有成功(字符串“+word+”仍然保留在输出中):

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.

我听说在某些情况下sed是必要的,但是如果可能的话,我希望使用Bash的build in find和replace。

1 个解决方案

#1


3  

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

#1


3  

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