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

Help with awk/gawk 2

Status
Not open for further replies.

sliverlight

Technical User
Nov 4, 2011
5
0
0
Hi,

Very much a newbie with gawk, so was wondering if anyone could help me. I need gawk to find the position of a string in a file and just print/output starting location it found it at.

I think gawk can probably do this, but didn't find any example/reference on it..

Thanks in advance for any help you can give..

Sliverlight
 
Hi

sliverlight said:
I need gawk to find the position of a string in a file
What kind of position ? Line number, character position in the line or absolute file position ?
Code:
awk '[COLOR=chocolate]match[/color][teal]([/teal][navy]$0[/navy][teal],[/teal][fuchsia]/and/[/fuchsia][teal])[/teal][teal]{[/teal][COLOR=chocolate]print[/color][green][i]"found on line"[/i][/green][teal],[/teal][blue]NR[/blue][teal],[/teal][green][i]"at position"[/i][/green][teal],[/teal][blue]RSTART[/blue][teal],[/teal][green][i]"file position"[/i][/green][teal],[/teal]l[teal]+[/teal][blue]RSTART[/blue][teal]}{[/teal]l[teal]+=[/teal][COLOR=chocolate]length[/color][teal]([/teal][navy]$0RS[/navy][teal])[/teal][teal]}[/teal]' /input/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].


Feherke.
 
Hi Feherke,

Thanks for the reply.. I just need to find the character position..

Thank you

Sliverlight
 
I just need to find the character position
So, only use RSTART

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Sorry, Actually I would need to try and find the position not on the line, but position in the file..

Is this possible?
 
Hi

Oops. Now I see that I posted the Awk code with the sample word I tested it. And the use of the word "and" may be misleading for beginners. So the word to search for has to be written in place of that "and".


Feherke.
 
Hi

If you have [tt]gawk[/tt] and need on the file position, there is shorter way :
Code:
awk -vRS='word_to_search_for' 'BEGIN[teal]{[/teal]l[teal]=[/teal]1[teal]}[/teal][blue]RT[/blue][teal]{[/teal][COLOR=chocolate]print[/color] l[teal]+=[/teal][COLOR=chocolate]length[/color][teal]([/teal][navy]$0[/navy][teal]);[/teal]l[teal]+=[/teal][COLOR=chocolate]length[/color][teal]([/teal][blue]RT[/blue][teal])[/teal][teal]}[/teal]' /input/file


Feherke.
 
Thanks for all the help Feherke. Your first post worked fine for me, butcheers for the shorter solution..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top