I want to replace last / by ,

Asked by At

I want to replace this:




With this sed command:

sed -i 's/\(.*\)\//\1,/'

This works in Unix. I tried to use this with system in Perl code, but it doesnt work. I request a solution using sed in Perl for the same.

2 Answers

ikegami On

First of all, the code you claim works doesn't.

$ printf 'a/b/c\n' | sed 's/(.*)//\1,/'
sed: -e expression #1, char 9: unknown option to `s'

It should be

$ printf 'a/b/c\n' | sed 's/\(.*\)\//\1,/'

You're asking how to execute this command from Perl. You can use the following:

 system('sed', '-i', '/\\(.*\\)\\//\\1,/', '--', $qfn)

Note that you can quite easily do the same task in Perl itself.

local @ARGV = $qfn;
local $^I = '';
while (<>) {
Tim Biegeleisen On

Here is way to do this in sed:

echo "365|366|367|369/0.18,improve/11.11," | sed 's/^\(.*\)\/\(.*\)$/\1,\2/'


The regex pattern used is:


This says to match and capture everything up until the last forward slash. Then, also match and capture everything after the last forward slash. Finally replace with the first two capture groups, but now separated by a comma.


  • forward slash / needs to be escaped by a backslash, to distinguish it from being the pattern delimiter
  • parentheses in the capture groups also need to be escaped with backslash