0

I have a file with many lines like below.

123)hfd)jggg)7584)abc
123)))7584)abc
)hfd)jggg)7584)cdf)))abc
)hfd)))abc

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

123)hfd)jggg)7584)abc
123)))7584)abc
)hfd)))abc
3
  • 2
    What if abc is part of a longer sequence of letters? E.g. Should )hfd)))abcdef be printed?
    – fra-san
    Commented Apr 1, 2021 at 11:07
  • 3
    Have you tried anything yourself? If so what problem did you encounter?
    – Ed Morton
    Commented Apr 1, 2021 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 )? Commented Apr 4, 2021 at 22:04

3 Answers 3

2

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”.

0
2

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.

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

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 '
  s/)/\n/4
  s/\nabc/)abc/p
' file

You must log in to answer this question.

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