10

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.

5 Answers 5

9

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.)

3
  • Good solution. I didn't know that $ARGV contains the name of the current file.
    – musiKk
    Jun 8, 2011 at 13:33
  • +1, feeding multiple files to a one-liner is very useful. Do you happen to know a way to get more files than *.css, for instance all the files in myfolder, recursing subdirectories? Yeah, that sounds like grep but perl can do more. :) For instance instead of *.css I tried ls *.css, it gave me a warning but did the work on the content of the files. Missing one ingredient do do this without a warning.
    – zx81
    Jul 12, 2014 at 5:37
  • @zx81: The *.cc isn't expanded by perl, but by the OS. Or in the case of Windows, not at all. Doing it inside the one-liner, when it just expecting to process per line, is more difficult, and more of a module deal. You could put something in a BEGIN block to load @ARGV, but it gets more complex.
    – Axeman
    Jul 13, 2014 at 16:04
6

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
5

You can stop the replacement after the first one:

perl -pi -e '$a=1 if(!$a && s/(width:).*;/$1 100%;/);' filename.css
2
  • 2
    Or, shorter: ... -e '!$x && s/.../.../ && ($x=1)'. Also this only works if there is only one file like in the question. Unfortunately it doesn't work for multiple files.
    – musiKk
    Jun 8, 2011 at 11:45
  • @musikk, that's why I contributed my answer, which would work for multiple files.
    – Axeman
    Jun 8, 2011 at 13:25
0

You can try this:

perl -pi -e 's/(width:).*;/$a?$&:++$a&&"$1 100%;"/e' filename.css
0

Maybe s/(width:).*;/$1 100%;/o would do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.