Link to home
Start Free TrialLog in
Avatar of steve wa
steve wa

asked on

Replace the specific position in a file

Need to read the file each line and  replace  the specific position if  first 2 position have specific value .

Inputfile  before modification


Inputfile  after modification

If position 1-2=22  replace  position 10-13 with 'y'

If position 1-2=77 replace  position 17-19 with 'x'

Avatar of ozo
Flag of United States of America image

perl -i -pe 's/(?<=^22.{8}).../yyy/;s/(?<=^77.{14}).../xxx/'   Inputfile
I notice one problem with your example and ozo's code.  You say if 22 then position 10-13 which is 4 characters (not 3) so the second line should be 22testingyyyy.

I assume you are using base-1 indexes (eg first character = 1) and not typical perl base-0 (eg first character = 0)?

If so, alternately:
perl -i -pe 'if (substr($_, 0, 2) eq "22") { substr($_,9,4) = "yyyy" } elsif (substr($_,0,2) eq "77") { substr($_,16,3) = "xxx" }'

Open in new window

Avatar of steve wa
steve wa


Thank you for correction in my example can I  put the code inside .pl script and passing inputfile as parameter?
./  test.txt

Code provided $ argv [0]
#!/usr/bin/perl -i.bak -p                                                                                                    
s/(?<=^22.{8}).../yyy/;s/(?<=^77.{14}).../xxx/  # modulo corrections in your example
I used the code provided by willcoxon.

Running like this.
Perl inputfile

Got the following error

do u need to predeclare pe?
String found where operator expected
Scalar found where operator expected
Avatar of wilcoxon
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
My original answer was for a one-liner run from the command-line.  You could do the minimal modifications (see below) indicated by ozo's answer or you could use the alternate script I provide above.
#!/usr/bin/perl -i -p
if (substr($_, 0, 2) eq "22") { substr($_,9,4) = "yyyy" } elsif (substr($_,0,2) eq "77") { substr($_,16,3) = "xxx" }

Open in new window

Used the multi line codr using foreach

use of uninitialized value $ argv [1] in concatenation (·) or string at
Could not tie : no such file or directoru at
Oops.  The places that have $ARGV[1] should be $ARGV[0] ($0 = program name but $ARGV[0] = first argument passed in).
Getting help very quickly.I thought i accepted  solution .Sorry for the delay.