bash - sed,只捕获数字

标签 bash sed numbers

我有这个文本文件:

some text A=10 some text
some more text A more text
some other text A=30 other text

我正在尝试使用 sed 仅捕获 A 的数值。使用此

cat textfile | sed -r 's/.*A=(\S+).*/\1/'

我得到:

10
some more text A more text
30

但我真正需要的是:

10
0
30

如果字符串 A= 不存在,则输出 0。我怎样才能做到这一点?

最佳答案

我不能单方面思考,所以这是我的方法:

while read line
do
grep -Po '(?<=A=)\d+' <<< "$line" || echo "0"
done < file

我正在使用后视 grep 来获取 A= 之后的任何数字。如果没有,||(else)将打印 0

关于bash - sed,只捕获数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051925/

相关文章:

bash - 查找多个文件的公共(public)行

linux - 如何替换linux中文件中包含 "/"的字符串?

mysql - 在 mysql_query 内部使用变量作为数组元素编号

bash - 在 bash 中检查输入是否为数字

linux - 为什么反引号中的 cd 永远不起作用

bash - Docker:https的wget不起作用

linux - 连接文件时奇怪的猫行为

bash - 这可以更快地完成吗(读取文件,替换 [sed],写入新文件)

linux - 为文件夹中的文件创建新的符号链接(symbolic link)

random - 使用QuasirandomGenerator(用于虚拟对象)