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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk or sed question 1

Status
Not open for further replies.

hok1man

Technical User
Feb 16, 2008
102
Hi guys,

echo "xx pts/19 Mar 4 03:16 (10.2.3.20)"

I would like to get :
10.2.3.20

I tried
nawk '{sub(/\(|\)/,"");print $NF}'
the result

10.2.3.20)

but if i tried nawk '{sub(/\)/,"");print $NF}'
result
(10.2.3.20

seems like my "or" "|" operator doesnt work,
anyone can nail it?

It would be nice if someone can tell me in sed as well but one liner..

thanks.
 
For [tt]sed[/tt]...
Code:
echo "xx  pts/19   Mar 4 03:16   (10.2.3.20)" | sed 's/^..*(//1;s/).*$//1'
 
Thanks Sambone,

what about if the logic I need is :
grab the last column or column 4 (in this case) and substitue (,) with nothing.

Thanks,
 
Alternatively
Code:
echo "xx  pts/19   Mar 4 03:16   (10.2.3.20)" | sed 's/^.*(\([^)]*\)).*$/\1/'

Sam's version replaces everything up to the opening bracket with nothing, and then everything after and including the closing bracket with nothing.

My version replaces a whole line consisting of anything ending in an opening bracket{.*(}, then some not closing brackets{[^)]*}, then a closing bracket followed by anything {).*}, with the bit between the brackets{\1}.

Whichever you understand best is fine.

For your awk version try
Code:
echo "xx  pts/19   Mar 4 03:16   (10.2.3.20)" |  awk  -F "[()]" '{print $2}'
you may have to try nawk for this. Notice that the field separator is a regular expression.

On the internet no one knows you're a dog

Columb Healy
 
You meen like this?
Code:
echo "xx    pts/19       Mar  4 03:16    (10.2.3.20)" | awk '{ print $NF }' | sed 's/[/(/)]//g'
10.2.3.20

Or a shorter version:
Code:
echo "xx    pts/19       Mar  4 03:16    (10.2.3.20)" | awk -F[\(\)] '{ print $2 }'
10.2.3.20
 
Ok, so you asked for
what about if the logic I need is :
grab the last column or column 4 (in this case) and substitue (,) with nothing.
Then try gsub which uses
Code:
echo "xx  pts/19   Mar 4 03:16   (10.2.3.20)" | awk '{gsub ( "[()]", "", $NF ); print $NF}'
The problem in your original version was that the first parameter to sub or gsub is a regular expression and the regexp for both brackets is [()]



On the internet no one knows you're a dog

Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top