1

If I have a file with for example the line:

hai hello test hey hi

I then want to search for the lines with test in it, and return the two surrounding strings hello and hey.

I can get the lines in which the search word is found using:

grep "test" $file"

But I can't figure out how to only get the two surrounding strings and do further things with the strings

2
  • Specify: and do further things with the strings Commented Feb 5, 2021 at 22:14
  • With strings you mean words, right? The o at the end of hello, the space between hello and test, or even the empty string are strings too, Commented Feb 5, 2021 at 22:15

1 Answer 1

3

With grep -o you can print only that part of a line that matches the given regex. Now you need a regex that matches test and its two surrounding words. To come up with something like this you have to know what a word is supposed to be, that is, what makes it different from any other string. Here we go with: "A word is a sequence of letters A-Za-z surrounded by anything that is not a letter"

grep -Eo '[A-Za-z]+[^A-Za-z]+test[^A-Za-z]+[A-Za-z]+' file

Note that this ignores all test that are not surrounded be words, for instance the lines test, test b, and a test. If you give a more detailed explanation of what you need I can adjust the regex.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.