Welcome to WebmasterWorld Guest from 54.205.74.11

Forum Moderators: coopster & jatar k & phranque

Help with file manipulation by position and line

   
9:48 pm on Mar 9, 2010 (gmt 0)

5+ Year Member



I'd like to have a small perl script go through some files in a directory and in each file do the following, look for the first line and retrieve the time and code and then insert a line immediately after it with those two variables but in a specific format.

Before:
TIME=20100118095957980|EVNT=HELLO67|CODE=1234567891011121314151617|OTHERSTUFF
TIME=20100118095957980|EVNT=MICKEY|NAME=MOREOTHERSTUFF

After have it look like:
TIME=20100118095957980|EVNT=HELLO67|CODE=1234567891011121314151617|OTHERSTUFF
TIME=20100118095957980|EVNT=MINNIE|CODE=1234567891011121314151617
TIME=20100118095957980|EVNT=MICKEY|NAME=MOREOTHERSTUFF

Any ideas?

Thanks!
-Troy
11:58 pm on Mar 9, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



that should be easy enough.

look at "open" to open the file,
<FILEHANDLE> (FILEHANDLE = the name you give open) to read from the file.
split to parse the output.
print to write to files.

since you probably don't want to mess around alot, it'd be best if you read from a file, parsed the first entry, wrote that + the next line, than read & wrote the rest of the file to a temporary file. once it's done, rename it with "rename".

look for the subroutine-names I mentioned with the command perldoc -f NAME or just ask google for "perldoc NAME".
2:15 pm on Mar 10, 2010 (gmt 0)

5+ Year Member



Glad to know this is going to be easier than I had thought. I have experience writing some shell scripts, but zero with perl.

So you're saying once I've written everything to the temporary file, then rename that back to the original file's name. Will the original file be overwritten at that point?

Thanks,
-Troy
3:11 pm on Mar 10, 2010 (gmt 0)

5+ Year Member



You probably want to use the File::Copy module, which should have come with your distribution of perl. Check out the 'move' and 'copy' methods, they do pretty much what they sound like--move a file from one name to another (rename essentially) and copy a file from one location to another. If the destination file name exists for either, it should overwrite whatever file is there. More info with the command 'perldoc -X File::Copy move' (or copy).
2:16 pm on Mar 18, 2010 (gmt 0)

5+ Year Member



As an update, I ended up doing what I needed with just a shell script and an awk command:

#!/bin/sh

FILELIST=`ls *.LOG`

for i in ${FILELIST}; do

awk 'NR == 1 {split($0,line1,"|"); print $0; print line1[1] "|EVNT=MINNIE|" line1[3]}; NR >= 2 {print $0}' $i > $i.NEW

done
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month