Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace only first match in multiple files with perl

I need to replace a bit of text in multiple css files, but ony the first occurence.

I've tried replacing with:

perl -pi -e 's/(width:).*;/$1 100%;/' filename.css

But this replaces the value after every occurrence of 'width:' in the file, even though i'm not using the /g modifier. I'm running this on a recent Ubuntu machine.

like image 376
Erwin Vrolijk Avatar asked Jun 08 '11 11:06

Erwin Vrolijk


3 Answers

You can stop the replacement after the first one:

perl -pi -e '$a=1 if(!$a && s/(width:).*;/$1 100%;/);' filename.css
like image 144
codaddict Avatar answered Oct 22 '22 21:10

codaddict


Nobody has addressed an implication of your actual title question. I recommend the same approach as used here, only modified:

perl -pie '!$subbed{$ARGV} and s/(width:).*;/$1 100%;/ and $subbed{$ARGV}++' *.css

The un-dimensioned $ARGV is the name of the current file. So for each file, you're replacing only the first occurrence. The "glob" *.css will send multiple files. If you do the scalar switch that other people are suggesting, you will modify only the first occurrence in the first file with that pattern. (Though, perhaps that is what you want.)

like image 39
Axeman Avatar answered Oct 22 '22 23:10

Axeman


If you read in paragraph mode, each file is only one line; hence the s/// without the /g modifier will replace the first instance in each file, then move to the next file:

perl -0777 -pi -e's/(width:).*;/$1 100%;/' *.css
like image 31
Altreus Avatar answered Oct 22 '22 21:10

Altreus