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.
With GNU grep, assuming there's at most one START...END
per line:
grep -oPm1 'STARTK.*?(?=END)' file
With awk, 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:
perl -lne 'do{ print $1; last } if /START(.*?)END/' file
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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP