2

I need to select and output into a file some text contained in a specific string.

Let's say the string is: ABCDEFGHIJKLMNOP

What would be a command to extract what is after ABCDEF and before K? (i.e. GHIJ only) to another file?

I tried with grep command but due to my poor understanding of its complexity it failed every time. I must be missing something very basic.

Thanks a lot in advance.

5

I am assuming that you are programming using a shell, such as bash.

You will need sed.

e.g.

sed -re 's/^ABCDEF(.*)K.*/\1/'

This uses grep to search and replace s/thing to find as regexp/thing to replace it with/

\1 means replace with 1st bracketed expression.

  • 1
    You don't need -e when you're using -r. And -r is GNU extension. There isn't GNU sed everywhere. -r is easier for understanding, but without it script is more portable. So, it can be sed 's/^ABCDEF\(.*\)K.*/\1/'. – ValeriyKr Jan 7 '17 at 14:42
4

On finding a match, grep prints the whole matched line. To make it print only the matched text, you can use -o switch. But, this prints the whole matched string within the line. To make it print what you need, you should use look-behind and look-ahead assertions. This requires a grep with PCRE support.

> grep -Po '(?<=ABCDEF).+(?=K)' <<< 'ABCDEFGHIJKL'
GHIJ

Explanation:

  • -P Enable perl compatible regular expression
  • -o Print only the matched text, not whole line
  • (?<=ABCDEF) Positive look-behind assertion for matching ABCDEF
  • (?=K) Positive look-ahead assertion for matching K
  • .+ Match everything between the above assertions
2

There is nothing wrong with either of the solutions posted, but you can do this in pure Bash if you like.

Given a string with your value:

echo $myStr 
ABCDEFGHIJKLMNOP

You can do:

echo $(expr match "$myStr" '.*F\(.*\)K.*')
GHIJ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.