We help IT Professionals succeed at work.

How to get the substring from a line.

radix655
radix655 asked
on
soemthing ..... [SourceSystemCode<25101>=789] something else.

How do I get the substring using awk

I am trying to use the index function.

awk '{ substr($0, index($0, "<25101>=")+8, not sure what index I should pass here... }'

Please suggest.
Comment
Watch Question

Hi radix,

In getting the index, what are you trying to achieve?  Are you wanting to return the whole line starting from "<25101>="?  If so, there are probably better ways.
If you could give us sample input and output, that would be great.

Author

Commented:
Sample Input:

[Source<25101>=sr2][SourceSystemCode<25102>=sr3]
[Source<25101>=sr3][OrderId<25102>=sr3]

Sample Output:
sr2
sr3

Author

Commented:
Please use this.

Sample Input:

[Source<25101>=sr2][SourceSystemCode<25102>=sr3]
[Source<25101>=source3][OrderId<25103>=101]

Sample Output:
sr2
source3
Thanks radix,

Does it have to be awk, or are sed or Perl OK?

Author

Commented:
It has to be awk please if possible.
Sorry radix,

I don't know much awk.  In Perl something like this should work:
    perl -ne '/<25101>=(\w+)/;print "$1\n"' inputfile
This assumes the output will always be letters, digits or '_'.
BTW, why do you prefer awk?
Top Expert 2011
Commented:
Say, your sample.txt contains
-----------
[Source<25101>=sr2][SourceSystemCode<25102>=sr3]
[Source<25101>=source3][OrderId<25103>=101]
------------

awk '{ match($0, /Source<25101>=(.*)]\[/, arr); print arr[1] }'  sample.txt

Author

Commented:
Amazing. Thanks.
Nice work, wesley.

radix, mine could be written better as:
    perl -pe 's/^.+<25101>=(.+?)].+/$1/' inputfile
Top Expert 2011

Commented:
@tel2
you might want to check radix first question, it is very challenging in shell script but easier in Perl.
http://www.experts-exchange.com/Programming/Languages/Scripting/Shell/Q_27239450.html
Thanks wesly,

Yes, I had seen that question, and was ignoring it because:
1. He hadn't responded to your request for more data yet.
2. I don't know if I have time.