Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sed to replace regex capture group?

Tags:

regex

bash

sed

I have a large file with many scattered file paths that look like

lolsed_bulsh.png 

I want to prepend these file names with an extended path like:

/full/path/lolsed_bullsh.png 

I'm having a hard time matching and capturing these. currently i'm trying variations of:

cat myfile.txt| sed s/\(.+\)\.png/\/full\/path\/\1/g | ack /full/path 

I think sed has some regex or capture group behavior I'm not understanding

like image 354
kevzettler Avatar asked May 25 '15 04:05

kevzettler


People also ask

Does sed work with regex?

Although the simple searching and sorting can be performed using sed command, using regex with sed enables advanced level matching in text files. The regex works on the directions of characters used; these characters guide the sed command to perform the directed tasks.

How do you replace something with sed?

Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do you use groups in sed?

Grouping can be used in sed like normal regular expression. A group is opened with “\(” and closed with “\)”. Grouping can be used in combination with back-referencing. Back-reference is the re-use of a part of a Regular Expression selected by grouping.

How do Capturing groups work in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .


1 Answers

In your regex change + with *:

sed -E "s/(.*)\.png/\/full\/path\/\1/g" <<< "lolsed_bulsh.png" 

It prints:

/full/path/lolsed_bulsh 

NOTE: The non standard -E option is to avoid escaping ( and )

like image 68
higuaro Avatar answered Sep 22 '22 11:09

higuaro