Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Column number of a search pattern

 
Pradeep Sahoo
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not sure if this is the right forum to ask this question. Still I thought I should try because I am desperately seeking a solution for this.
I want to search for a pattern in a single line of text and to identify the column position if this pattern is found in the text.
E.g.
If the text is
THIS IS HELLO WORLD and I search for the pattern HELLO, I should get the output as 9 (Position of H assuming 'T' in THIS has a position 1)
I am working on Solaris - which means I have all the standard tools e.g. sed, awk, grep etc available. But I am not sure of the logic.
I would be greatful if anybody can help on this.
Many Thanks in advance,
Pradeep
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18014
47
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a rough stab in Perl:

This is untested code, but it should be reasonably close.
 
Leslie Chaim
Ranch Hand
Posts: 336
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Perl there's no need to satb
a dart can do as well...
<code><pre>perl -lne 'print length ($`) + 1 if /HELLO/' file</code></pre>
or if you want the line thing:
<code><pre>perl -lne 'print "$.:", length ($`) + 1 while /HELLO/g'</code></pre>
[ July 28, 2003: Message edited by: Leslie Chaim ]
[ July 29, 2003: Message edited by: Leslie Chaim ]
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 11854
185
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does Solaris come with Perl already installed?
If not, then you could try using awk:
<code><pre>echo "This is Hello World" | awk '{print index($0, "Hello");}'
9</pre></code>
If the string you are looking for is variable, you could set it programatically:
<code><pre>SEARCH_FOR="Hello";
echo "This is Hello World" | awk -vFIND="$SEARCH_FOR" '{print index($0, FIND);}'
9</pre></code>
Regards, Andrew
 
Pradeep Sahoo
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Tim, Leslie and Andrew,
Its incredible to see so many different solutions for such a trivial problem.
Thanks once again,
Pradeep
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18014
47
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I liked the length(&`).
It's Perl! There's More Than One Way To Do It! (TM)
[ July 29, 2003: Message edited by: Tim Holloway ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic