I want to replace last / by ,

Asked by At

I want to replace this:

a/b/c|d,385|386|387|388|389|390|391|392|393|394|395|396|397|398|399|400/0.162,214|229|254|255|270|272|276|287|346|356|361|362|365|366|367|369/0.18,improve/11.11,

With:

a/b/c|d,385|386|387|388|389|390|391|392|393|394|395|396|397|398|399|400/0.162,214|229|254|255|270|272|276|287|346|356|361|362|365|366|367|369/0.18,improve,11.11,

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

3
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,/'
a/b,c

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 (<>) {
    s{^.*\K/}{,};
    print;
}
0
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/'

      365|366|367|369/0.18,improve,11.11,

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.

Notes:

  • 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