击:在命令行输出字符串的一部分抓斗 [英] Bash: Grab part of string from a command line output
问题描述
我在CentOS的运行命令,让我一个字符串的输出,我想抓住该输出的某一部分,将其设置为一个变量。
I am running a command in CentOS that gives me an output of a string and I want to grab a certain part of that output and set it to a variable.
我运行命令EBI-描述-ENV。
I run the command ebi-describe-env.
我的输出如下:
ApplicationName | CNAME | DATECreated | DateUpdated | Description | EndpointURL |
EnvironmentID | EnvironmentName | Health | Stack | Status | TemplateName |
Version Label --------------------------
Web App | domain.com | 2012-02-23 | 2012-08-31 | |
anotherdomain.com | e-8sgkf3eqbj | Web-App-Name | Status |
Linux | Ready | N/A | 20120831 - daily
我要抢 20120831 - 每日
'的字符串(此字符串会改变的,但在同一个地方停留),并将其设置为一个变量的一部分。
I want to grab the '20120831 - daily
' part of the string (this string will always change but stays in the same place) and set it to a variable.
原本我以为我可以使用grep或者sed和之后的每个打印线'|'而13号线设置为变量。
Originally I thought I could use grep or sed and print a line after each '|' and set the 13th line to a variable.
我是很新的bash脚本编程,所以任何帮助将是巨大的。谢谢你。
I'm very new to bash scripting, so any help would be great. Thank you.
推荐答案
使用 AWK
:
awk -F"|" '{print $NF}'
这将工作:
echo " Web App | domain.com | 2012-02-23 | 2012-08-31 | | anotherdomain.com |
e-8sgkf3eqbj | Web-App-Name | Status | Linux | Ready | N/A |
20120831 - daily" | awk -F"|" '{print $NF}'
和收益率:
20120831 - daily
的要分配给一个变量的(的data.txt
包含你的字符串只是为了简单起见,它也可以在回声
以上):
To assign to a variable (data.txt
contains your string just for simplicity, it also works the echo
above):
$ myvar=$(awk -F"|" '{print $NF}' data.txt)
$ echo $myvar
20120831 - daily
说明的
在 -F
设置输入分隔符,在这种情况下 |
。 NF
是指输入字段数内置 AWK
变量, $
在变量前的最后场访问该元件,也就是说,在这种情况下,在该行( $ NF
)。
the -F
sets the input field separator, in this case to |
. NF
is a built-in awk
variable that denotes the number of input fields, and the $
in front of the variable accesses that element, i.e., in this case the last field in the line ($NF
).
的或者的:你可以抓住每一个由白色空间( AWK
默认)分离这一最后三个领域:
Alternatively: You could grab each of the last three fields separated by white space (the awk
default) with this:
awk '{print $(NF-2), $(NF-1), $NF}'
这篇关于击:在命令行输出字符串的一部分抓斗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!