Swati Majumdar
Swati Majumdar

Reputation: 57

Replace command not working

I want to replace this code

 for($counter=0;$counter<10;$counter++)
 {
     $yyarr[$counter]=$counter+2004;
 }

with

 for($counter=2004;$counter<=date("Y");$counter++)
 {
     $yyarr[$counter-2004]=$counter;
 }

I am using

sed -e 's/for\(\$counter=0;\$counter<10;\$counter++\)\n\t+{\n\t+\$yyarr\[\$counter\]=\$counter+2004;\n\t+}/for\(\$counter=2004;\$counter<=date\("Y"\);\$counter++\)\n{\$yyarr\[\$counter-2004\]=\$counter;\n}/g'

But can't get it through. Trailing whitespace needs to be ignored.

Upvotes: 3

Views: 557

Answers (2)

devnull
devnull

Reputation: 123678

sed processes lines of data. As such, the way you're attempting to search/replace your pattern wouldn't work. You could make use of hold space to search your pattern, though.

The following might work for you:

sed -n '1h; 1!H; ${g; s/\s*for(\$counter=0;\$counter<10;\$counter++)\s*\n\s*{\s*\n\s*\$yyarr\[\$counter\]=\$counter+2004;\s*\n}/\nfor($counter=2004;$counter<=date("Y");$counter++)\n{\n\t$yyarr[$counter-2004]=$counter;\n}/ p}' filename

Upvotes: 1

Antarus
Antarus

Reputation: 1621

sed ':a;N;$!ba;s/for($counter=0;$counter<10;$counter++)\n{\n    $yyarr\[$counter\]=$counter+2004;\n}/for($counter=2004;$counter<=date("Y");$counter++)\n{\n    $yyarr\[$counter-2004\]=$counter;\n}/g' file

You are facing problem with new line replacement \n. The above code will fix it.

Upvotes: 2

Related Questions