use strict;
use warnings;
while (<DATA>) {
s/a/x/g unless $. & 1;
print;
}
__DATA__
Anyone know a way to apply a
substitution in a file to every
other line rather
than the hole file?
Prints:
Anyone know a way to apply a
substitution in x file to every
other line rather
thxn the hole file?
DWIM is Perl's answer to Gödel
| [reply] [d/l] [select] |
perl -i.bak -nle 's/search/replace/g unless $. & 2; print' file(s)
The above will apply the changes in line numbers 1,3,5,7,......
perl -i.bak -nle 's/search/replace/g unless $. & 1; print' file(s)
The above will apply the changes in line numbers 2,4,6,8,......
NOTE: Based on the idea from Re: Search and replace in all odd lines by GrandFather | [reply] [d/l] [select] |
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
adapting your one-liner to just print the lines gives
$ perl -nle 'print unless $. & 2;' lines.txt
line 1
line 4
line 5
line 8
line 9
Did you actually test your adaptation of GrandFather's idea before posting? Changing between odd and even is as simple as if $. & 1 and unless $. & 1. Perhaps you could have a look at "Bitwise And" in perlop to further your understanding. Cheers, JohnGG
Update: Corrected typo.
Update 2: Corrected huge balls-up, thanks fenLisesi. Where did I get "2 is binary 100" from?
Update 3: And thanks clinton, saw your reply after /msg from fenLisesi | [reply] [d/l] [select] |
perl -i.bk -lne 's/foo/bar/g if $.%2;print;' foo.txt
This will substitute all the foo's into bar's that appears in odd lines of the file foo.txt (saving a backup of the original file in foo.txt.bk)
Hope this helps
citromatik | [reply] [d/l] |
for i in 1 2 3 4 5; do perl -e'print "$_\n" foreach 1..$ARGV[0]' $i >
+$i;done
Once you run that, you've got 5 files in the current directory, 1..5, where 1 contains 1 line, and 5 contains 5...
perl -ne'printf "File: $ARGV \$.: %2d real line: $_",$. if $. & 1' 1 2
+ 3 4 5
This results in:
File: 1 $.: 1 : real line: 1
File: 2 $.: 3 : real line: 2
File: 3 $.: 5 : real line: 2
File: 4 $.: 7 : real line: 1
File: 4 $.: 9 : real line: 3
File: 5 $.: 11 : real line: 1
File: 5 $.: 13 : real line: 3
File: 5 $.: 15 : real line: 5
So in file 2 and 3, you get the even lines, because file 1 had an odd # of lines. If we had a file 6, its even lines would get printed instead of the odd ones, since the (1+2+3+4+5) is an odd #.
Fun, eh? :)
| [reply] [d/l] [select] |
If you are doing from command line, you can use perl -n -e '<substitute logic> if $.%2>0
Ranjan | [reply] [d/l] |