Take the 2-minute tour ×

So I want to automate a manual task using shell scripting, but I'm a little lost as to how to parse the output of a few commands. I would be able to this in other languages without a problem, so I'll just explain what I'm going for in psuedo code and provide an example of the cmd output I'm trying to parse.

Example of output:

Chg 2167467 on 2012/02/13 by user1234@filename 'description of submission'

What I need to parse out is '2167467'. So what I want to do is split on spaces and take element 1 to use in another command. The output of my next command looks like this:

Change 2167463 by user1234@filename on 2012/02/13 18:10:15

   description of submission

Affected files ...

... //filepath/dir1/dir2/dir3/filename#2298 edit

I need to parse out '//filepath/dir1/dir2/dir3/filename#2298' and use that in another command. Again, what I would do is remove the blank lines from the output, grab the 4th line, and split on space. From there I would grab the 1st element from the split and use it in my next command.

How can I do this in shell scripting? Examples or a point to some tutorials would be great.

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

Its not clear if you want to use the result from the first command for processing the 2nd command. If that is true, then

targString=$( cmd1 | awk '{print $2}')
command2 | sed -n "/${targString}/{n;n;n;s@.*[/][/]@//@;p;}"

Your example data has 2 different Chg values in it, (2167467, 2167463), so if you just want to process this output in 2 different ways, its even simpler

cmd1 | awk '{print $2}'
cmd2 | sed -n '/Change/{n;n;n;s@.*[/][/]@//@;p;}'

I hope this helps.

share|improve this answer
all of the ideas were pretty good, but this one helped the most. i ended up finding xargs, went with this, and it works perfectly: <my cmd> | awk '{print $2}' | xargs <my second cmd> | grep '^\.\.\.' | awk '{print $2}' –  user797963 Feb 16 '12 at 18:23
add comment

I'm not 100% clear on your question, but I would use awk.


share|improve this answer
add comment

Your first variable would look something like this

temp="Chg 2167467 on 2012/02/13 by user1234@filename 'description of submission'"

To get the number you want do this:

temp=`echo $temp | cut -f2 -d" "`

Let the output of your second command be saved to a file something like this

command $temp > file.txt

To get what you want from the file you can run this:

temp=`tail -1 file.txt | cut -f2 -d" "`
rm file.txt

The last block of code gets the last nonwhite line of the file and delimits on the second set of white spaces

share|improve this answer
add comment

Your Answer


