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!

Searching text file for a string in a fixed position

Status
Not open for further replies.

229257

Programmer
Apr 23, 2002
54
GB
Hi,
I was wondering if someone could help me? I want to search through a text file looking for a certain string just like you would with 'grep' but i only want to return results if the string pattern appears in a fixed position on the file.

E.g. i want to searh for a username in the passwd file e.g. 'adj' but i only want the line to be returned if this username appears at character positions 1 to 3.

Is there such a command or method that could do this for me?
Thanks
00229257
 
That works great but how could how could search for that string in a different position e.g. positions 6 to 8?

Thanks

229257
 
grep '^.....adj'

There is also an awk solution:

cat /etc/passwd|awk '{if (substr($0,6,3)=="adj") print}'

HTH,

p5wizard
 
[tt]cat /etc/passwd|awk '{if (substr($0,6,3)=="adj") print}'[/tt]

[tt]cat[/tt] isn't needed. Even if [tt]Awk[/tt] couldn't read files, [tt]cat[/tt] wouldn't be needed, because one could say: [tt]awk '....' <myfile[/tt].
Code:
awk 'substr($0,6) ~ /^adj/' /etc/passwd
 
In this case we needed to use a form of cat (ypcat);

ypcat passwd | awk '{if (substr($0,1,3)=="adj") print}'

Becuause we have several UNIX server's and the one we are using for this project is not the NIS controller.

ypcat either contacts the NIS controller or has a shadow copy of the passwd from the NIS controller.
 
@futurelet,

I KNOW that cat isn't needed, I just didn't want anyone to misread or mistype and OUTPUT TO /etc/passwd instead of reading from it...

Whenever a config file is being queried, I PREFER to use cat and pipe the output to a command if that command can't read the file itself. I'll take the overhead of one more process.


HTH,

p5wizard
 
Since cat is needed, I believe this is an idiomatic Awk solution:
Code:
ypcat passwd | awk 'substr($0,6) ~ /^adj/'
[tt]{ if [/tt] and [tt] print } [/tt] aren't needed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top