Bash:使用参数扩展查找和替换 [英] Bash: Find and replace using Parameter Expansion
问题描述
我要替换输入,
find_string:@include circle-progress(38px,30px,#4eb630)
find_string: @include circle-progress(38px, 30px, #4eb630)
并输出
Output_string:@include circle-progress(38px,30px)
Output_string: @include circle-progress(38px, 30px)
使用 $ {find_string//pattern/replacement_string}
,其中pattern是,,#[A-Fa-f0-9] [A-Fa-f0-9] [A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9])))'
我提供
using ${find_string//pattern/replacement_string}
where pattern is , , #[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9]?([A-Fa-f0-9])))'
that I supply.
在下面的代码中,当我从文件中读取代码行时,仅打印匹配 pattern
的 line
,即 find_string
我想要输出字符串.
In the code below, simply the line
matching pattern
is printed i.e find_string
, when I read lines of code from a file, whereas I want the output_string to be printed.
pattern="@include circle-progress\(([0-9]{1,3}px, ){2}#[A-Fa-f0-9]
{3,6}\)" /*regex the matches find_string*/
replace_glob=', #[A-Fa-f0-9][A-Fa-f0-9][A-Fa-f0-9]?([A-Fa-f0-9]?([A-
Fa-f0-9]?([A-Fa-f0-9])))' /*glob pattern in the string to be replaced*/
while IFS='' read -r line || [[ -n "$line" ]]; do
if [[ $line =~ $pattern ]]
then
echo "${line//$replace_glob/}"
fi
done < "$1"
推荐答案
参数扩展中的模式不是正则表达式,但遵循与全局模式匹配相同的规则:
The pattern in parameter expansion is not a regular expression but follows the same rules as glob pattern matching:
-
*
:匹配任何字符序列 -
?
:匹配任何字符 -
[
..]
:集合中的任何字符 -
[^
..]
或[!
..]
:任何未设置的字符
*
: matches any character sequence?
: matches any character[
..]
: any character in set[^
..]
or[!
..]
: any character not in set
带有shell选项: shopt -s extglob
,具有更多功能,但少于正则表达式
with shell option : shopt -s extglob
, some more features but less than regular expressions
-
@(
..|
..)
:匹配一次 -
?(
..|
..)
:匹配0或1次 -
*(
..|
..)
:匹配0次或多次 -
!(
..)
:与所有匹配,除了
@(
..|
..)
: match any once?(
..|
..)
: match any 0 or 1 times*(
..|
..)
: match any 0 or more times!(
..)
: matches all except
但是bash支持一些基本的正则表达式,以下方法应该起作用:
However bash supports some basic regex, following should work:
string='@include circle-progress(38px, 30px, #4eb630)'
pattern='@include circle-progress\([ ]*[0-9]{1,3}px,[ ]*[0-9]{1,3}px(,[ ]*#[A-Fa-f0-9]{3,6}[ ]*)\)'
[[ $string =~ $pattern ]] && echo "${string//"${BASH_REMATCH[1]}"}"
这篇关于Bash:使用参数扩展查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!