sed command to print first instance of pattern in range

The following text is in testFile.txt:

one 5
two 10
three 15
four 20
five 25
six 10
seven 35
eight 10
nine 45
ten 50

I'd like to use sed to print the first occurance of search pattern /10/ in a given range. This command is to be run against large log files, so to optimize efficiency, I'd like to use sed's q command to stop processing after reaching the first matching pattern. For example, to print the first occurance of /10/ in the range of lines from 2 to end-of-file, it should function like the following.

sed -n '2,${/10/p;}' testFile.txt | head -1

This will generate output of only the following line:

two 10

Sed version: installed with OS, AIX 5.3 TL 12.

try:

sed -n '2,${/10/!n; p; q; }' testFile.txt

Just add the 'q;' option to quit after the first match:

sed -n '2,${/10/p;q;}' testFile.txt
two 10
sed -n '/10/ {p;q}' file

I'm nt cmfortable wid sed. Bt i thunk it can be done using for loop n grep. As i'm posting through mobile so code isn't testd. Plz modify to meet ur need

for $ln `cat testfile.txt`
{
  num=echo $ln | grep -Po *[0-9]{2}
 if [ $num = '10' ]
 echo $ln
exit 0
fi
}

it'll search upto first occurance n then exit. Plz revrt incase of furthr explanation

Your suggestions unconditionally abort after reading line 2, and will generate incorrect output if the first instance of matching text within the range does not occur on the first line of that range.

This suggestion does not implement the range restriction.

A correct, sed-only solution:

sed -n '2,${/10/!d; p; q;}'

If the end of the range is not the end of the file, then an additional check is needed to avoid reading the remainder of a long file which does not match. Taking the range to be 2,50:

sed -ne '2,50{/10/!d; p; q;}' -e '50q'

Regards,
Alister

1 Like

No point in printing before or reading after:

sed '
  /10/{
    p
    q
   }
  d
 '

The original problem statement restricts matches to a range. In the OP's example, it is 2,$.

Regards,
Alister

Two subranges will do as well:

sed -n '2,${/10/{p;q}}'  file

And, add a second condition if the range ends before file end, as alister proposed.

Might be faster to say 1d than 2,${...}.

1 Like