Sed: syntax error with unexpected "("

Mar*_*ari 0 perl runtime-error sed

I've got file.txt which looks like this:

C00010018;1;17/10/2013;17:00;18;920;113;NONE
C00010019;1;18/10/2013;17:00;18;920;0;NONE
C00010020;1;19/10/2013;19:00;18;920;0;NONE
Run Code Online (Sandbox Code Playgroud)

And I'm trying to do two things:

  1. Select the lines that have $id_play as 2nd field.
  2. Replace ; with - on those lines.

My attempt:

#!/usr/bin/perl

$id_play=3;
$input="./file.txt";
$result = `sed s@^\([^;]*\);$id_play;\([^;]*\);\([^;]*\);\([^;]*\);\([^;]*\);\([^;]*\)\$@\1-$id_play-\2-\3-\4-\5-\6@g $input`;
Run Code Online (Sandbox Code Playgroud)

And I'm getting this error:

sh: 1: Syntax error: "(" unexpected
Run Code Online (Sandbox Code Playgroud)

Why?

psx*_*xls 5

你必须转义@字符,在某些情况下添加2个反斜杠(感谢ysth!),在sed之间添加单引号并使其也过滤行.所以替换为:

$result = `sed 's\@^\\([^;]*\\);$id_play;\\([^;]*\\);\\([^;]*\\);\\([^;]*\\);\\([^;]*\\);\\([^;]*\\);\\([^;]*\\)\$\@\\1-$id_play-\\2-\\3-\\4-\\5-\\6-\\7\@g;tx;d;:x' $input`;
Run Code Online (Sandbox Code Playgroud)

PS.你打算做的事情可以用更干净的方式实现,而无需调用sed和使用拆分.例如:

#!/usr/bin/perl
use warnings;
use strict;

my $id_play=3;
my $input="file.txt";
open (my $IN,'<',$input);
while (<$IN>) {
    my @row=split/;/;
    print join('-',@row) if $row[1]==$id_play;
}
close $IN;
Run Code Online (Sandbox Code Playgroud)