bash 如何从bash shell脚本中的一行中提取一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7971506/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:09:01  来源:igfitidea点击:

how to get extract a word from a line in bash shell script

bash

提问by jch

i want to extract a word from a sentence in bash script .it uses both coma and space as separators.

我想从 bash 脚本中的句子中提取一个单词。它同时使用逗号和空格作为分隔符。

ex:- date=crossed 122 name=foo , userid=234567 , sessionid=2233445axdfg5209  associd=2

I have above sentence in which the interesting part is name=foo .the key name is always same but the string foo may vary. also other parameters may or may not be there .

我有上面的句子,其中有趣的部分是 name=foo 。键名总是相同的,但字符串 foo 可能会有所不同。其他参数可能存在也可能不存在。

i need to extract above key value pair. so output would be :

我需要提取上面的键值对。所以输出将是:

name=foo

what is the best way to do it in shell script?

在shell脚本中执行此操作的最佳方法是什么?

thanks!

谢谢!

回答by glenn Hymanman

grep is useful here:

grep 在这里很有用:

grep -o 'name=[^ ,]\+'

回答by Jon O.

If you know that the value after namewill never contain spaces or quotes, and there are no other complications, you could do this with a sedone-liner:

如果您知道 after 的值name永远不会包含空格或引号,并且没有其他复杂情况,您可以使用sed单行代码执行此操作:

sed -e 's/^.*\(name=[^ ,]*\).*$/\1/'

sed -e 's/^.*\(name=[^ ,]*\).*$/\1/'

That just says to replace the entire line with the part that matches name=followed by any number of non-comma, non-space characters.

这只是说用匹配的部分替换整行,name=后跟任意数量的非逗号、非空格字符。

This not going to be terribly robust if there are possibilities like name="quoted string"or name=string\ with\ escaped\ spaces. But it will work for the limited case.

如果存在name="quoted string"或 之类的可能性,这将不会非常强大name=string\ with\ escaped\ spaces。但它适用于有限的情况。

If you want to store the result in a shell variable you might do something like (in bash)

如果你想将结果存储在一个 shell 变量中,你可能会做一些类似的事情(在 bash 中)

pair=$(echo $input | sed -e 's/^.*\(name=[^ ,]*\).*$//')
echo $pair

which prints name=foo, as intended.

name=foo按预期打印。

Tested with GNU sed 4.2.1 and Bash 4.2.10

使用 GNU sed 4.2.1 和 Bash 4.2.10 测试

回答by Debugger

If "name=foo" is always in the same position in the line you could simply use: awk '{print($3)}', that will extract the third word in your line which is name=fooin your case.

如果 "name=foo" 总是在行中的相同位置,您可以简单地使用: awk '{print($3)}',这将提取您行中的第三个单词,这就是name=foo您的情况。