Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash sed non-greedy matching

Here is my text:

1a.begin /path/1a.file
2bx.begin2 /path/my/2bx.file2

and the expected output is

begin /path/1a.file
begin2 /path/my/2bx.file2

Here I want to do it by using non-greedy matching by sed. (The default matching by sed is greedy and all the 1a. and 2bx. will be removed)

Hence I tried the command:

echo -e "1a.begin /path/1a.file\n2bx.begin2 /path/my/2bx.file2"|sed 's/$.*[^\.]\.//g'

where I used the $.* to match all strings starting at the head of a line. I used [^\.] to prevent greedy matching all . in a line (see similar method in https://www.unix.com/shell-programming-and-scripting/133641-non-greedy-sed.html) But it did not change the text.

So where is my script wrong?

like image 847
user13846961 Avatar asked Jan 22 '26 21:01

user13846961


1 Answers

  • Your start of line anchor $ is wrong, you should be using ^
  • You use a greedy match .* up to the last period .

Using sed

$ sed 's/^[^.]*\.//' input_file
begin /path/1a.file
begin2 /path/my/2bx.file2
like image 123
HatLess Avatar answered Jan 25 '26 16:01

HatLess



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!