Operating System - Linux
1752574 Members
4636 Online
108788 Solutions
New Discussion юеВ

Re: file content replacement

 
SOLVED
Go to solution
Pando
Regular Advisor

file content replacement

dear gurus,

I would like to ask how can i check if the ENDTIME field inside the file (please see attached file) has the correct format already and not "" - data? Subsequenty, If the data format is not correct the particular line content needed to be replaced.

I have attached a sample file. From the filename (DEV_1560_DC_1107_210610_S2.TDF), i need to extract the field 4th (1107) and 5th (210610) in the filename and place it in the ENDTIME line as

ENDTIME,20051107-210610

The 2005 is a prefix to the 4th field in the filename.

Maximum points for all correct answers.
4 REPLIES 4
Muthukumar_5
Honored Contributor

Re: file content replacement

Using awk as,

#awk 'BEGIN{split(ARGV[1],a,"_");}{if ( $0 ~ /ENDTIME/ ) {print "ENDTIME,2005"a[4]"-"a[5]; } else { print;}}' DEV_1560_DC_1107_210610_S2.TDF > test.TDF
# mv test.TDF DEV_1560_DC_1107_210610_S2.TDF

hth.
Easy to suggest when don't know about the problem!
Muthukumar_5
Honored Contributor

Re: file content replacement

Is 2005 - current year? If so,

With scripting:

#!/bin/ksh
# test.ksh

FILE=DEV_1560_DC_1107_210610_S2.TDF
PATTERN=$(echo "`date +'%Y'``echo $FILE | awk -F_ '{ print $4"-"$5 }'`")

sed -e "s/^ENDTIME,.*/ENDTIME,$PATTERN/g" $FILE > test.TDF
mv test.TDF > $FILE

# exit
exit 0

hth.
Easy to suggest when don't know about the problem!
Muthukumar_5
Honored Contributor
Solution

Re: file content replacement

You can use perl as,

# perl -ni -e 'BEGIN{ $p1="-";($p0,$p2)=(split /_/,$ARGV[0])[3,4];}{ if (/ENDTIME/){print "ENDTIME,$p0$p1$p2\n"}else {print;} }'

It will update the contents also.

hth.
Easy to suggest when don't know about the problem!
john korterman
Honored Contributor

Re: file content replacement

Hi Fernando,

if I get it correct - there is a bit of testing to be done.
Attached, please find an approach using standard commands; the script should be able to handle all files listed in the directory which you have to specify (FULL_PATH_TO_FILES).
However, I would recommend that you, if you at all dare to uncomment the mv command line(!), enter a different destination path, in order not to overwrite your original files.


regards,
John K.
it would be nice if you always got a second chance