I have a file with many lines like below.


I have to output the lines with abc exactly after 4th occurrence of the ) [closing parenthesis]. So the output should be:

  • 2
    What if abc is part of a longer sequence of letters? E.g. Should )hfd)))abcdef be printed?
    – fra-san
    Apr 1 at 11:07
  • 3
    Have you tried anything yourself? If so what problem did you encounter?
    – Ed Morton
    Apr 1 at 23:01
  • Do you guarantee that ")abc" will always be the last four characters of the lines you want? If not, what can come after?  More letters (as in fra-san's question?  Maybe a fifth )? Apr 4 at 22:04

grep is sufficient:

grep -E '^([^)]*\)){4}abc'

This looks for lines starting with a sequence of any characters other than “)”, followed by a “)”, repeated four times, followed by “abc”.


In awk, you can set an arbitrary field separator.  In this case you want to use ) as the field separator; that can be done with -F')'.  The first field is what comes before the first separator, the second field is what comes between the first and second separator, and so on.  You want to query for the string "abc" in the fifth field ($5).

awk -F')' '$5 == "abc"' file

awk works line-by-line in like 'CONDITION { COMMAND }' – it will execute the command(s) if the condition is met.  Without condition, the command is executed on every line; without command, it will print the whole line if the condition is met.

  • Thank you, that worked
    – Sri
    Apr 1 at 11:26

With the GNU sed editor. Try to place a marker at the fourth occurence of the character ) and in the next step try to take it away. Print when successful.

sed -ne '
' file

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .