[英]Shell script : How to cut part of a string
我有以下字符串
â â³ 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"="
将使用=
作为分隔符来剪切步骤#2的输出,并获得第二列( -f2
) 如果您还希望获得id=
,则:
$ cat so.txt | awk '{ print $7 }'
id=9
id=10
使用正则表达式捕获ID号,并用数字替换整行。 应该这样做(将所有内容匹配为“ id =“,然后匹配任意数量的数字,然后匹配行的其余部分):
sed -e 's/.*id=\([0-9]\+\).*/\1/g'
对每一行执行此操作,您将获得ID列表。
Perl解决方案:
perl -nE 'say $1 if /id=(\d+)/' filename
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
你可以有awk
做到这一切,而不使用cut
:
awk '{print substr($7,index($7,"=")+1)}' inputfile
您可以使用split()
代替substr(index())
。
假设输入
{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
也可以看看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.