问题
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.
I run the command ebi-describe-env.
My output as follows:
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
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.
Originally I thought I could use grep or sed and print a line after each '|' and set the 13th line to a variable.
I'm very new to bash scripting, so any help would be great. Thank you.
回答1:
Using awk
:
awk -F"|" '{print $NF}'
this will work:
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}'
and yield:
20120831 - daily
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
Explanation
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
).
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}'
回答2:
Levon's answer works great, but I just had to show there are always other ways with shell scripting.
This one uses the basic tool called cut
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" | cut -d"|" -f13
回答3:
I know that this has been accepted already, but here's how to do it in pure bash:
string="Web App | domain.com | 2012-02-23 | 2012-08-31 | | anotherdomain.com | e-8sgkf3eqbj | Web-App-Name | Status | Linux | Ready | N/A | 20120831 - daily"
myvar="${string##*| }"
echo "$myvar"
来源:https://stackoverflow.com/questions/12223615/bash-grab-part-of-string-from-a-command-line-output