我有以下字符串
â â³ eGalax Inc. USB TouchController id=9 [slave pointer (2)]
â â³ eGalax Inc. USB TouchController id=10 [slave pointer (2)]
我想获取id列表,如何使用sed或其他方法实现?
我将你的示例内容复制到了一个名为so.txt
的文件中。
$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10
解释:
cat so.txt
命令将文件的内容输出到 stdout
。 awk '{ print $7 }'
命令将打印第七列,即包含 id=n
的列cut -f2 -d"="
命令将使用等号 (=
) 作为分隔符剪切第二列输出 (-f2
)如果您想要同时获取 id=
,那么:
$ cat so.txt | awk '{ print $7 }'
id=9
id=10
sed -e 's/.*id=\([0-9]\+\).*/\1/g'
awk
而无需使用cut
来完成所有操作:awk '{print substr($7,index($7,"=")+1)}' inputfile
split()
代替substr(index())
。$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
一个Perl解决方案:
perl -nE 'say $1 if /id=(\d+)/' filename
{Anything}id={ID}{space}{Anything}
{Anything}id={ID}{space}{Anything}
--
#! /bin/sh
while read s; do
rhs=${s##*id=}
id=${rhs%% *}
echo $id # Do what you will with $id here
done <so.txt
或者如果它总是第七个字段
#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt
参见
awk
和cut
的解释。我曾尝试在另一个用例中实现类似的功能,但是在awk手册和教程上遇到了很多困难。非常感谢您花时间解释您的代码! - Kevin G.