KodeFor.Me
KodeFor.Me

Reputation: 13511

Using sed to replace string in file by using regex capture group

I start by saying I am very new on shell script so please don't shoot me !! :)

I have a file that contains the following text:

1   :    / 
2   :    /string-1/ 
4   :    /string-2/ 
5   :    /string-3/

and I like to remove the end slashes of the strings so the result should be like that :

1   :    / 
2   :    string-1 
4   :    string-2 
5   :    string-3

I have try that by using the sed as following:

local_export_folder="/home/merianos/Documents/repositories/DatabaseBackup/tmp"

sed -i -e 's/\/([^\/]+)\//\1/' ${local_export_folder}/blogs.csv

but this doesn't work.

Am I doing anything wrong ?

Upvotes: 1

Views: 1702

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74595

This works for me:

sed 's#/\([^/]*\)/#\1#' file

This captures any content between two forward slashes. The replacement is the content, without the slashes.

One issue that you may have been facing is that + (one or more) isn't understood by all versions of sed. I have changed it to a * (which means zero or more), which is more widely recognised. If you prefer, you could use the POSIX-compliant \{1,\} to mean one or more instead.

Output:

$ sed 's#/\([^/]*\)/#\1#' file
1   :    /
2   :    string-1
4   :    string-2
5   :    string-3

Depending on your version of sed, you may be able to use the -r or -E switch to enable extended regular expressions. This means that parentheses don't need escaping to be used as capturing groups and the + is understood:

sed -r 's#/([^/]+)/#\1#' file

Upvotes: 4

Related Questions