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

How to grep string in a fixed position?

Status
Not open for further replies.

praise12

IS-IT--Management
Mar 17, 2002
17
US
Hey there
How to use grep to search for a pattern/string in a fixed length file eg.in position 10-20 or field 3 only?
Thanks for your help in advance!
 
For a fix colum this works
grep &quot;..........<string>&quot; file
 
grep &quot; string&quot; <file> will return all the rows which containing the search string found. But, what I need is able to pull out the string/pattern from certain position, such as field 3 or position 1 to 20, can I use grep here? and if yes, how to identify the position or field in the same 'grep' command?
 
Hi,

With grep you cannot specify the positions where to search for the pattern.

A solution is to use awk.
Look at this little example:

--- xgrep ---
if [ $# -lt 3 ] ; then
echo &quot;Usage: $0 pattern start end [file...]&quot; 2>&1
exit 1
fi
Pattern=&quot;$1&quot;
Start=$2
End=$3
let Len=End-Start+1
shift 3
awk -v START=$Start -v LEN=$Len -v PATTERN=$Pattern '
substr($0,START,LEN) ~ PATTERN ' $*
-- End of xgrep ---

For example, to search the pattern &quot;M[01][0-9]&quot; in position 10-12 of file :

xgrep &quot;M[01][0-9]&quot; 10 12 inputfile

Jean Pierre.
 
If would have thought that misercord's example above would work fine. To find lines in file.txt where the string 'help' starts in the 8 character I would type:

grep '.......help' file.txt

I don't have a UNIX system here at the moment (reinstalling HPUX as I type) so I can't test it, sorry. Mike
&quot;Experience is the comb that Nature gives us after we are bald.&quot;

Is that a haiku?
I never could get the hang
of writing those things.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top