Match from beginning to word as long as there are no . in between: Convert grep -Po command to sed

Viewed 328

I have made the following command to be able to match the string from the beginning of the line until the first occurrence of ".enabled" as long as there are no "." in between.

grep -Po '^\K[\w-]*?(?=\.enabled)'

input:

a-b-c.a.enabled.xxx.xx
a-b-c.a.b.enabled.xxx.xx
a-b-c.enabled.xxx.xx

output:

a-b-c

It runs properly on my local env with grep v3.1 but on Busybox v1.28.4 it says "grep: unrecognized option: P"

For that reason, I would like to convert this command to sed. Any input would be really helpful.

3 Answers

You can use

awk -F'.' '$2 == "enabled"{print $1}' file
sed -n 's/^\([^.]*\)\.enabled.*/\1/p' file

See the online demo.

Details:
awk:

  • -F'.' - the field separator is set to a .
  • $2 == "enabled" - if Group 2 value is enabled, then
  • {print $1} - print Field 1 value
    sed:
  • -n - suppresses default line output in the sed command
  • s/^\([^.]*\)\.enabled.*/\1/p - finds any zero or more chars other than . at the start of string (placing them into Group 1, \1), then a .enabled and then the rest of the string and replaces with the Group 1 value, and prints the resulting value.

With your shown samples, you could try following.

awk -F'\\.enabled' '$1~/^[-_[:alnum:]]+$/{print $1}'  Input_file

Explanation: Simply making field separator as .enabled for all the lines here. Then in main program checking condition if 1st field is having --or_` or alphanumeric then print 1st field here.

You may use this equivalent sed of your grep -P command:

sed -nE 's/^([-_[:alnum:]]+)\.enabled.*/\1/p' file

a-b-c

Details:

  • -n: Suppress notmal output
  • -E: Enables extended regex mode
  • ([-_[:alnum:]]+): -_[:alnum:]]is equivalent of [-\w] or [-_a-zA-Z0-9]. It matches 1+ of these characters and captures them in group #1
  • \.enabled.*: matches .enabled followed by 0 or more of any string
  • \1: is replacement string that put value captured in capture group #1 back in replacement
Related