bash 如何使用 SED linux 获取第一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2482817/
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
How to get the first numbers with SED linux
提问by Yannis Assael
"00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter" how can i get the first numbers until VGA with SED in Bash script? Thanks!
“00:02.0 VGA 兼容控制器:InnoTek Systemberatung GmbH VirtualBox 图形适配器”如何在 Bash 脚本中获得带有 SED 的 VGA 之前的第一个数字?谢谢!
回答by ghostdog74
$ s="00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter"
$ echo $s| sed 's/\(.*\)VGA.*//'
00:02.0
$ echo $s| sed 's/\([0-9]\+:[0-9]\+.*\)VGA.*//'
00:02.0
$ echo $s| sed 's/VGA.*//'
00:02.0
or awk
或 awk
$ echo $s| awk '{print }'
00:02.0
回答by Paused until further notice.
This will also work, but it relies on there being a space after the numbers you want.
这也可以,但它依赖于你想要的数字后面有一个空格。
sed 's/ .*//'
回答by Eric Eijkelenboom
echo '00:02.0 VGA compatible bla bla bla' | sed -e 's/\(^[0-9:\.]*\).*//'
回答by Gregory Pakosz
sed -e 's/\([0-9][0-9]:[0-9][0-9]\.[0-9]\).*//'
will keep the numbers.
将保留数字。
In a script you're likely going to pipe the command that returns you the string to sed, like
在脚本中,您可能会通过管道传输将字符串返回给 sed 的命令,例如
#!/bin/sh
echo "00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter" | sed -e 's/\([0-9][0-9]:[0-9][0-9]\.[0-9]\).*//'
which gives
这使
00:02.0
回答by mdeous
imho it would be simplier to use awk instead of sed, using awk for what you want would give this:
恕我直言,使用 awk 而不是 sed 会更简单,将 awk 用于您想要的会给出:
echo '00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter' | awk '{print }'
much less complicated than using sed, isn't it?
比使用 sed 简单得多,不是吗?
回答by Chris Johnsen
It looks like you are parsing lspcioutput. If so, you might want to look into the -moption that should be a bit easier to parse. If you are intent on using sedwith the default output format, then you might be able to do what you want like this:
看起来您正在解析lspci输出。如果是这样,您可能想要查看-m应该更容易解析的选项。如果您打算将sed与默认输出格式一起使用,那么您可以像这样执行您想要的操作:
echo '00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter' |
sed -e 's/\([0-9a-fA-F][0-9a-fA-F]\):\([01][0-9a-fA-F]\)\.\([0-7]\) .*/ /' |
while read bus slot func; do
echo "bus: $bus; slot: $slot; func: $func"
done
If you are really only reading one line, you could do it without the while loop, but I included it in case you are actually wanting to parse multiple lines of lspcioutput.
如果你真的只阅读一行,你可以不使用 while 循环,但我将它包含在内,以防你真的想要解析多行lspci输出。
回答by Idelic
X="00:02.0 VGA compatible ..."
set $X; echo
回答by WisdomFusion
try, sed -e 's/(^[0-9:.])./\1/' urfile
尝试, sed -e 's/(^[0-9:.])./\1/' urfile

