Bash: Grab part of string from a command line output

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 19:38:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!