Linux Shell 脚本:如何剪切字符串的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3742292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell script : How to cut part of a string
提问by deimus
I have following string
我有以下字符串
a a3 eGalax Inc. USB TouchController id=9 [slave pointer (2)]
a a3 eGalax Inc. USB TouchController id=10 [slave pointer (2)]
and would like to get the list of id ? How this can be done using sed or something else ?
并想获得 id 的列表?如何使用 sed 或其他方法完成此操作?
采纳答案by Manoj Govindan
I pasted the contents of your example into a file named so.txt
.
我将您示例的内容粘贴到名为so.txt
.
$ cat so.txt | awk '{ print }' | cut -f2 -d"="
9
10
Explanation:
解释:
cat so.txt
will print the contents of the file tostdout
.awk '{ print $7 }'
will print the seventh column, i.e. the one containingid=n
cut -f2 -d"="
will cut the output of step #2 using=
as the delimiter and get the second column (-f2
)
cat so.txt
将文件的内容打印到stdout
.awk '{ print $7 }'
将打印第七列,即包含id=n
cut -f2 -d"="
将使用=
作为分隔符的步骤 #2 的输出并获得第二列 (-f2
)
If you'd rather get id=
also, then:
如果你id=
也想得到,那么:
$ cat so.txt | awk '{ print }'
id=9
id=10
回答by bluebrother
Use a regular expression to catch the id number and replace the whole line with the number. Something like this should do it (match everything up to "id=", then match any number of digits, then match the rest of the line):
使用正则表达式来捕捉 id 号并用数字替换整行。应该这样做(匹配所有内容到“id=”,然后匹配任意数量的数字,然后匹配该行的其余部分):
sed -e 's/.*id=\([0-9]\+\).*//g'
Do this for every line and you get the list of ids.
对每一行执行此操作,您将获得 id 列表。
回答by sid_com
A perl-solution:
一个 perl 解决方案:
perl -nE 'say if /id=(\d+)/' filename
回答by Paused until further notice.
You can have awk
do it all without using cut
:
您可以在awk
不使用的情况下完成所有操作cut
:
awk '{print substr(,index(,"=")+1)}' inputfile
You could use split()
instead of substr(index())
.
您可以使用split()
代替substr(index())
.
回答by ghostdog74
$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10
回答by frayser
Assuming input of
假设输入
{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
Or if it's always the 7th field
或者如果它总是第 7 个字段
#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt
See Also
也可以看看