匹配后 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
Bash print word after match
提问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 long
error.
当我尝试这个时,我收到一个sed: can't read prints_output: File name too long
错误。
Does sed
only take in a filename? I am running a hive query to desc formatted table
and storing the results in output
like so:
是否sed
只需要在文件名?我正在运行一个 hive 查询desc formatted table
并将结果存储在output
像这样:
output=`hive -S -e "desc formatted table"`
output
is 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 ;}'