在Bash脚本中返回正则表达式匹配项,而不是替换它 [英] Return a regex match in a Bash script, instead of replacing it

查看:104
本文介绍了在Bash脚本中返回正则表达式匹配项,而不是替换它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想匹配Bash脚本中的一些文本.我尝试使用sed,但似乎无法使其仅输出匹配项,而不是将其替换为某些内容.

I just want to match some text in a Bash script. I've tried using sed but I can't seem to make it just output the match instead of replacing it with something.

echo -E "TestT100String" | sed 's/[0-9]+/dontReplace/g'

哪个将输出TestTdontReplaceString.

不是我想要的,我希望它输出100.

Which isn't what I want, I want it to output 100.

理想情况下,它将所有匹配项放在一个数组中.

Ideally, it would put all the matches in an array.

文本输入以字符串形式出现:

Text input is coming in as a string:

newName()
{
 #Get input from function
 newNameTXT="$1"

 if [[ $newNameTXT ]]; then
 #Use code that im working on now, using the $newNameTXT string.

 fi
}

推荐答案

echo "TestT100String" | sed 's/[^0-9]*\([0-9]\+\).*/\1/'

echo "TestT100String" | grep -o  '[0-9]\+'

用于将结果放入数组中的方法在某种程度上取决于如何检索实际数据.您的问题中没有足够的信息来指导您.但是,这是一种方法:

The method you use to put the results in an array depends somewhat on how the actual data is being retrieved. There's not enough information in your question to be able to guide you well. However, here is one method:

index=0
while read -r line
do
    array[index++]=$(echo "$line" | grep -o  '[0-9]\+')
done < filename

这是另一种方式:

array=($(grep -o '[0-9]\+' filename))

这篇关于在Bash脚本中返回正则表达式匹配项,而不是替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆