简体   繁体   English

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

[英]Bash variable search and replace instead of sed

See Code Review 参见代码审查

See Github Project 参见Github项目

I need to parse out instances of +word+ line by line (replace +word+ with blank). 我需要逐行解析+word+实例(用空白替换+word+ )。 I'm currently using the following (working) sed regex: 我目前正在使用以下(有效的)sed正则表达式:

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内置的find和replace方法。

The substitution in parameter expansion doesn't use regular expressions, but patterns . 参数扩展中的替换不使用正则表达式,而是使用patterns To get closer to regular expressions, you can turn on extended patterns: 为了更接近正则表达式,您可以打开扩展模式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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