匹配后 Bash 打印单词

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

Bash print word after match

regexbashsedmatch

提问by raphnguyen

I have a variable that stores the output of a file. Within that output, I would like to print the first word after Database:. I'm fairly new to regex, but this is what I've tried so far:

我有一个存储文件输出的变量。在该输出中,我想在Database:. 我对正则表达式相当陌生,但这是我迄今为止尝试过的:

sed -n -e 's/^.*Database: //p' "$output"

When I try this, I am getting a sed: can't read prints_output: File name too longerror.

当我尝试这个时,我收到一个sed: can't read prints_output: File name too long错误。

Does sedonly take in a filename? I am running a hive query to desc formatted tableand storing the results in outputlike so:

是否sed只需要在文件名?我正在运行一个 hive 查询desc formatted table并将结果存储在output像这样:

output=`hive -S -e "desc formatted table"`

outputis then set to the result of that:

output然后设置为结果:

...
# Detailed Table Information
Database:               sample_db
Owner:                  sample_owner
CreateTime:             Thu Feb 26 23:36:43 PDT 2015
LastAccessTime:         UNKNOWN
Protect Mode:           None
Retention:              0
Location:               maprfs:/some/location
Table Type:             EXTERNAL_TABLE
Table Parameters:
...

回答by Jonathan Leffler

Superficially, you should be using:

从表面上看,您应该使用:

hive -S -e "desc formatted table" |
sed -n -e 's/^.*Database: //p'

This will show the complete line containing Database:. When you've got that working, you can eliminate the unwanted material on the line too.

这将显示包含Database:. 当你开始工作时,你也可以消除线上不需要的材料。

Alternatively, you could use:

或者,您可以使用:

echo "$output" |
sed -n -e 's/^.*Database: //p'

Or, again, given that you're using Bash, you could use:

或者,再一次,假设您使用的是 Bash,您可以使用:

sed -n -e 's/^.*Database: //p' <<< "$output"

I'd use the first unless you need the whole output preserved for rescanning. Then I'd probably capture the output in a file (with tee):

除非您需要保留整个输出以供重新扫描,否则我会使用第一个。然后我可能会在文件中捕获输出(使用tee):

hive -S -e "desc formatted table" |
tee output.log |
sed -n -e 's/^.*Database: //p'

回答by Potter_nsit

Try using egrep:

尝试使用 egrep:

egrep -oh 'Database:[[:blank:]][[:alnum:]]*[[:blank:]]' <output_file> | awk  '{print ;}'