I'm automating a hardware task and one of the tools I'm using outputs a list of serial devices to connect to. The format is as follows:
我正在自动执行硬件任务,我正在使用的工具之一输出要连接的串行设备列表。格式如下:
Available device (a) : /dev/stuff
可用设备(a):/ dev / stuff
Available device (b) : /dev/watermelon
可用设备(b):/ dev / watermelon
Available device (c) : /dev/stuff
可用设备(c):/ dev / stuff
I need to find the line that "watermelon" occurs on and then extract the letter inside the parentheses. So in this case, it would be "b". However, the order is not guaranteed to be preserved (that's why I have to search by "watermelon").
我需要找到“西瓜”出现的行,然后在括号内提取字母。所以在这种情况下,它将是“b”。但是,订单不能保证保留(这就是为什么我必须通过“西瓜”搜索)。
1 个解决方案
#1
0
You can do it very easily with sed
and a backreference, e.g.
您可以使用sed和反向引用非常轻松地完成此操作,例如:
$ sed -n '/watermelon/s/^[^(]*(\([^)]*\).*$/\1/p' file
b
Where
-
sed -n
suppress normal printing of lines, -
/watermalon/
match the line with watermelon, -
s/find/replace/
- the normal substitute option- find
^[^(]*(\([^)]*\).*$
what is in parens and save as 1st reference - replace
\1
with what was saved as first referent
找到^ [^(] *(\([^]] * \)。* $什么是parens并保存为第一个参考
将\ 1替换为保存为第一指示物的内容
- find
-
p
print the result.
sed -n禁止正常打印行,
/ watermalon /与西瓜匹配,
s / find / replace / - 正常的替代选项找到^ [^(] *(\([^]] * \)。* $什么是parens并保存为第一个参考替换\ 1与保存为第一参考的内容
p打印结果。
If you must use bash, then you can do it with [[ ]]
and the =~
operator and parameter expansion with substring removal, e.g.
如果必须使用bash,则可以使用[[]]和=〜运算符以及子字符串删除的参数展开,例如
while read -r line; do
[[ $line =~ watermelon ]] && { tmp="${line#*\(}"; echo "${tmp%)*}"; }
done < file
output
b
#1
0
You can do it very easily with sed
and a backreference, e.g.
您可以使用sed和反向引用非常轻松地完成此操作,例如:
$ sed -n '/watermelon/s/^[^(]*(\([^)]*\).*$/\1/p' file
b
Where
-
sed -n
suppress normal printing of lines, -
/watermalon/
match the line with watermelon, -
s/find/replace/
- the normal substitute option- find
^[^(]*(\([^)]*\).*$
what is in parens and save as 1st reference - replace
\1
with what was saved as first referent
找到^ [^(] *(\([^]] * \)。* $什么是parens并保存为第一个参考
将\ 1替换为保存为第一指示物的内容
- find
-
p
print the result.
sed -n禁止正常打印行,
/ watermalon /与西瓜匹配,
s / find / replace / - 正常的替代选项找到^ [^(] *(\([^]] * \)。* $什么是parens并保存为第一个参考替换\ 1与保存为第一参考的内容
p打印结果。
If you must use bash, then you can do it with [[ ]]
and the =~
operator and parameter expansion with substring removal, e.g.
如果必须使用bash,则可以使用[[]]和=〜运算符以及子字符串删除的参数展开,例如
while read -r line; do
[[ $line =~ watermelon ]] && { tmp="${line#*\(}"; echo "${tmp%)*}"; }
done < file
output
b