1

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 ?

4
  • Your title is misleading, there are no 'regular expression variables' here. Can you be more specific than 'this doesn't work'? Commented Dec 29, 2014 at 14:14
  • What I try to describe be the title is how to use the content of the parentheses as the replacement text. I don't know how to write that title better. Commented Dec 29, 2014 at 14:15
  • 1
    The part between the parentheses is called a capture group. Hope that helps. Commented Dec 29, 2014 at 14:17
  • Thanks !! :) That's really help's ;) Commented Dec 29, 2014 at 14:18

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, while I used my regex, finally you helped me a lot, because I see that you escape the capture group parentheses too. So, when I escaped the parenthesis worked for me too.
And in case this is helpful, to destructively change the input, use: sed -i 's#/([^/]*)/#\1#' file
@Merianos I have mentioned a way of using the parentheses without having to escape them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.