0

I have a sample textfile(test_long_sentence.txt) below and I want to grep all the lines that contain test1 excluding unwanted data.

How do I grep the data before the quote closes?

test_long_sentence.txt

This is some unwanted data blah blah blah

20  /test1/catergory="Food"
20  /test1/target="Adults, \"Goblins\", Elderly,
Babies, \"Witch\",
Faaries"
20  /test1/type="Western"

This is some unwanted data blah blah blah

20  /test1/theme="Halloween"

Command:

grep "test1" test_long_sentence.txt

Actual Output:

20  /test1/catergory="food"
20  /test1/target="Adults, \"Goblins\", Elderly,
20  /test1/type="Western"
20  /test1/theme="Halloween"

Expected Output:

20  /test1/catergory="food"
20  /test1/target="Adults, \"Goblins\", Elderly,
Babies, \"Witch\",
Faaries"
20  /test1/type="Western"
20  /test1/theme="Halloween"

Ps: I have no control in editing the test_long_sentence.txt. So please, do not ask me to edit it to a single line.

Jojoleo
  • 171
  • 2
  • 12
  • Possible duplicate of [How to show only next line after the matched one?](https://stackoverflow.com/questions/7451423/how-to-show-only-next-line-after-the-matched-one) – jww Feb 12 '18 at 02:55
  • Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. – jww Feb 12 '18 at 02:56
  • @jww I dont really think it is a duplicate but i will post it to Unix Stack Exchange – Jojoleo Feb 12 '18 at 03:24

1 Answers1

0

This is not perfect, but it might work for you:

grep -A 1 "test1" test_long_sentence.txt | grep -E 'test1|"$'
  • grep -A 1 fetches one extra line after the match
  • grep -E ... will retain the matching line and the next line, only if the next line ends with a double quote

It assumes that the text that you want to extract doesn't exceed two lines.

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Thanks for your response! I have edited the text_long_sentence.txt above. grep -A 2 might seemed good till grep -E 'test1|"$'. What if the data spans across more then 2 lines and the second doesn't end with a quote? Sorry that I didn't come across my mind initially but the data could be pretty long. – Jojoleo Feb 12 '18 at 02:50