0

Background:

(1) I have a data set of scientific notation:

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2.503832e-05, 1.433673e-05, 2.557402e-05, 
    3.081098e-05, 4.044465e-05, 2.480817e-05, 2.681778e-05, 1.533265e-05, 
    2.3156e-05, 3.193812e-05, 5.325314e-05, 1.639066e-05, 0, 0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 2.259782e-05, 0.0004197799, 2.65868e-05, 0.0002485498, 
    3.485129e-05, 2.454055e-05, 0.0002096856, 0.0001910835, 1.969936e-05, 
    2.974743e-05, 8.983165e-05, 0.0004263787, 0.0004444561, 0.000241368, 0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

(2) I aim to add a certain values to those non-zero values.

(3) Thanks to the warm help from other stack-exchange users, I got a solution by using:

perl -pe 's/([0-9.e-]+)/$1 == 0 ? $1 : .001 + $1/ge' < input.txt > output.txt

My Problem:

I have two following-up questions:

(Q1) I know that from sed, we can, says, extract few lines from an input file and save those lines to an output file by:

sed -n (123,345p) input.txt > output.txt

Which extracted lines 123 to Line 345 from input.txt and saved to ouput.txt.

However, I do not have ideas how I can modify the above perl script to add numbers to the specified lines of the ascii file.

(Q2) Can I add an option to the above perl script such that my changes are directly added to the input.txt file? I have tried to modify -pe as -pei but it seems does not work.

Any help will be appreciated.

Anthon
  • 79,293
nam
  • 137

1 Answers1

2

Simply:

perl -i.bak -pe 's/([0-9.e-]+)/$1 == 0 ? $1 : .001 + $1/ge if 123..345' input.txt
  • -i.bak make perl edit file in-place and make a backup file input.txt.bak (I invite you to read this question)

  • if 123..345 using flip-flop operator, emulate line-range operator of sed, awk.

cuonglm
  • 153,898