Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How change a word in the same file on the same position

Status
Not open for further replies.

jarod

Programmer
Aug 10, 2001
6
US
How can I change a word by an another word in:THE SAME FILE and ON THE SAME POSITION.
Here is my file:
aaaaa bbbbbb ccccc
dddddd eeeee
12 0.12345 "Apr 15 2002 xx:xx:xx:xxxAM"
20 0.9999 "Apr 15 2002 xx:xx:xx:xxxAM"

Be aware:
Only the line begining with 20 must be change and only the word 2002 must be change.

Ps: I already found a part of the solution (identification of the line and substitution)

Thanks in advance for your help
 
If you use <> to read in the file, such as

while (<>)

then add a '-i' or a '-i.bak' to the first line of your script. This makes changed in place and the '-i.bak' will make a bakup file of your original with the .bak extension. But you have to replace every line that you read in, even if you don't change it.

#!/usr/bin/perl -w -i.bak

while (<>) {

# replace 2002 if line begins with 20
print;
}

BTW, the extension '.bak' can be anything you want it to.

jaa
 
Even better my son:

perl -pi.bak &quot;s/oldword/newword/ if /^20/;&quot; filename.log

The -p switch adds the while(<>){} loop for you, this makes one lines all the more tasty.

--jim
 
Thanks for your information.
The problem is that the line does not start everytime with 20. In fact I must read all file and save in a variable only the last line like:
20 0.9999 &quot;Apr 15 2002 xx:xx:xx:xxxAM&quot;

Before the process:
aaaaa bbbbbb ccccc
dddddd eeeee
12 0.12345 &quot;Apr 15 2002 xx:xx:xx:xxxAM&quot;
20 0.9999 &quot;Apr 15 2002 xx:xx:xx:xxxAM&quot;
fffff ggggg
hhhhhh iiiiiiii

After the process:
aaaaa bbbbbb ccccc
dddddd eeeee
12 0.12345 &quot;Apr 15 2002 xx:xx:xx:xxxAM&quot;
20 0.9999 &quot;Apr 15 2050 xx:xx:xx:xxxAM&quot;
fffff ggggg
hhhhhh iiiiiiii


Thanks for your help,
Jarod





 
When you say that the line doesn't always start with 20, do you mean it might start with whitespace before the 20 or that it might start with another number besides 20?

If, judging from your example, the '20' may have preceeding whitespace then just change the regex that Jim posted to be:

perl -pi.bak &quot;s/2002/2050/ if /^\s*20/;&quot; filename.log

jaa
 
Or do you mean that the line that you want to edit isn't the line that starts with 20, rather it's the always the LAST line that is in the specified &quot;Log&quot; format...?

--jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top