Link to home
Start Free TrialLog in
Avatar of cyrobinson
cyrobinson

asked on

read a file and replace certain lines

All,

How would I read through a file and replace lines that contain a certain word?

e.g.

The following test file is in existence

name,  age,  interests
bill,  30 ,  Football
Mark,  15 ,  Computers
Jill,  10 ,  Nothing!

If I wanted to loop through this file and replace the line containing Mark's age and interests with something else how would I go about that?

Avatar of ahoffmann
ahoffmann
Flag of Germany image

perl -i.bak -pe 's/Mark/whatever/' file
Avatar of rj2
rj2

If you want to change Marks age to 35 and his interests to Women, you could try sample below.
Just paste the line into a DOS prompt. Change filename from data.txt to correct filename in your system.

perl -i.bak -pe "s/Mark,(\s*)\d*(\s*),(\s*)\w*/Mark,\1\Q35\E\2,\3Women/" data.txt

If you don't need to preserve the spaces you could try the somewhat simpler line below instead.

perl -i.bak -pe "s/Mark,.*/Mark,35,Women/" data.txt

Avatar of cyrobinson

ASKER

i was more wanting to loop over each line of an input file from within a perl script and modify each line like that
ASKER CERTIFIED SOLUTION
Avatar of rj2
rj2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>  was more wanting to loop over each line of an input file from within a perl script and modify each line like that

This is exactly what my suggestion does :-)