1

I have following string in text file:

^25555555~BIG^20200629^20022222^20200629^55555555^^^DI^00~CUR^ZZ^USD

and want to fetch string between BIG^ and ^00 i.e. 20200629^20022222^20200629^25523652^^^DI. I tried to use following command but it is not working, may be because of special character caret ^.

echo "^25555555~BIG^20200629^20022222^20200629^25523652^^^DI^00~CUR^ZZ^USD" | grep -o -P '(?<=BIG^).*(?=^00)'

I tried removing caret from search and it is working but need to include caret in my search:

echo "^25555555~BIG^20200629^20022222^20200629^55555555^^^DI^00~CUR^ZZ^USD" | grep -o -P '(?<=BIG).*(?=00)'

above command returns: ^20200629^20022222^20200629^55555555^^^DI^

How to fetch part of string from string containing special character caret ^ using grep?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
PravinB
  • 11
  • 1

2 Answers2

2

The regex pattern should be BIG\^(.*)\^00 will grab this:

BIG^20200629^20022222^20200629^55555555^^^DI^00

and the item in group (1) is your value 20200629^20022222^20200629^55555555^^^

0

You can use

grep -oP 'BIG\^\K.*?(?=\^00)'

See the regex demo.

Details:

  • BIG\^ - a BIG^ string
  • \K - a match reset operator that omits the text matched so far from the match memory buffer
  • .*? - any zero or more chars other than line break chars as few as possible
  • (?=\^00) - a positive lookahead that requires a ^00 string immediately to the right of the current location.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563