regex - Why the following variations of s/g from command line are wrong? -
i have small file follows:
$ cat text.txt vacation cat test
this command substitutes occurrences of cat cat correctly wanted:
$ perl -p -i -e ' s/cat/cat/g; ' text.txt
but why following 2 mess file up?
following deletes contents of file
$ perl -n -i -e ' $var = $_; $var =~ s/cat/cat/g; ' text.txt
and 1 not substitution correctly
$ perl -p -i -e ' $var = $_; $var =~ s/cat/cat/g; ' text.txt $ cat text.txt cation cat test
why? messing here?
-p
prints out each line automatically (the contents of $_
, contains current line's contents), re-populates file (due -i
flag in use), -n
loops on file -p
does, doesn't automatically print. have yourself, otherwise overwrites file nothing. -n
flag allows skip on lines don't want re-insert original file (amongst other things), whereby -p
, you'd have use conditional statements along next()
etc. achieve same result.
perl -n -i -e ' $var = $_; $var =~ s/cat/cat/g; print $var; ' text.txt
see perlrun.
in last example, -p
automatically print $_
(the original, unmodified line). doesn't auto-print $var
@ all, in case, you'd have print $var
in example above, you'd both original line, , modified 1 printed file.
you're better off not assigning $_
if you're doing overwriting file. use is. eg. (same first example):
perl -p -i -e ' s/cat/cat/g; ' text.txt
Comments
Post a Comment