perl or sed replace lines only if for all files

Hi Everyone,

[root@]# cat 3
a
b
[root@]# cat 4
a
b

[root@]# perl -p -i -e "s/.*/c/ if $.==2" *

[root@]# cat 3
a
c
[root@]# cat 4
a
b

how to make the file "4", the 2nd line also change to "c"? i thought i already use "*" for all files. Please advice.

Thanks

Try:

for i in *; do perl -p -i -e "s/.*/c/ if $.==2" $i; done
1 Like

the variable $. will not reset to 1 once the next file starts. It will continue counting.

1 Like
perl -i -pe'
  s/.*/c/ if $. == 2;
  close ARGV if eof;
  '  *

Ruby(1.9+)

$ ruby -i -pne '$_="c\n" if $.==2; ARGF.close if ARGF.eof'  3 4
1 Like