TransWikia.com

sed expression to extract group of the first match

Unix & Linux Asked on October 31, 2021

I have the following text:

somegarbageSTARTfirstgroupENDsomeendgarbage
someohtergarbageSTARTsecondgroupENDsomeotherendgarbage
...

I would like to extract firstgroup using sed.

I tried sed -nr 's/.*START(.*)END.*/1/p', but it doesn’t work, it extracts all matches not only the first one.

2 Answers

With GNU , assuming there's at most one START...END per line:

grep -oPm1 'STARTK.*?(?=END)' file

With , assuming the first occurrence is on the first line and that there's no END before the first START and that there's no START in the value to be returned:

awk -F'START|END' '{print $2;exit}' file

or

awk -F'START|END' '$0 ~ FS {print $2;exit}' file

With :

perl -lne 'do{ print $1; last } if /START(.*?)END/' file

Output

firstgroup

Answered by Gilles Quenot on October 31, 2021

sed -nr '/.*START(.*)END.*/{s/.*START(.*)END.*/1/p;q}'
# or (probably faster)
sed -nr 's/.*START(.*)END.*/1/p; t quit; b end; : quit; q; : end;'

Answered by Hauke Laging on October 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP