Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to split variable line with varied delimiters

Status
Not open for further replies.

patwat

Programmer
Apr 18, 2008
4
US
What I want to do:
Parse the output from a verbose "grep" command and get just certain pieces of information.

Sample output from grep:
user123 12101 <variable collection of unwanted stuff> -nproduction_WebLive <maybe more unwanted stuff>

The problem:
I want the pid (here "12101") which is always field 2 using the standard awk delimiter of spaces, but I also want to grab that which is preceded by "-n" and it is not always in the same spot. I know about using "-F" to specify a different delimiter, but have not figured out how to switch delimiters after grabbing the desired pid.

Desired output:
Using the above example, I would like to see "12101 production_WebLive
 
There's no need for grep when you're using awk, because it has the same search capability built-in.

e.g.

Code:
ps -ef | awk '
    /searchstring/ {
        n=$0
        # strip off everything up to and including -n
        sub("^.*-n","",n)
        # strip off everything after space following -n parameter
        sub(" .*$","",n)
        print $2,n
    }
'

Annihilannic.
 
Judging from the structure, and the error I got, I am guessing this needs to be within a script rather than being command line doable?

Thanks for the tip. I'll give it a shot and let you know how it turns out.
 
It should work from the command line, if you're prepared to type that much!

I laid it out like that for clarity, you could equally write:

Code:
ps -ef | awk '/searchstring/ { n=$0; sub("^.*-n","",n); sub(" .*$","",n); print $2,n }'

Annihilannic.
 
Duh! I forgot the semi-colons. I think I like the script idea better, that way others can use it, too.
 
Added the "x" to the ps parameters and this works like a charm.

Thank you so much
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top