5

I need to search a pattern I/f in a file between some range of lines and quit on the first match. For that I am using sed command like this

sed -n '14922,28875{\|I/f|=}' file.txt

It actually prints all the occurence between line 14922 to 28875 but I want only first occurence.

I have one alternate solution for this which is to pipe line the output and use head command. Something like that

sed -n '14922,28875{\|I/f|=}' file.txt | head -n 1

It works but just wondering if it is possible without head command. I searched on the internet and I found we use q character but somehow I am not getting right place to insert that in my command. Can anyone please help me in this

vivek
  • 153

1 Answers1

5

Use {=;q} instead of =:

sed -n '14922,28875{\|I/f|{=;q}}' file.txt

If there is no match, sed will keep reading the file without a chance of producing any output. This is sub-optimal. Make it quit after processing the 28875th line:

sed -n '14922,28875{\|I/f|{=;q}};28875q' file.txt

Note in your example with head -n 1, if head does its job and exits then sed will notice this only when it tries to write a second line to its stdout (compare this). This means sed will keep processing the file until the second match is found or till the end. In this aspect it's even worse than my sub-optimal solution with q.