1830237 Members
12742 Online
109999 Solutions
New Discussion

shell script help

 
hamlite42
Occasional Advisor

shell script help

Trying to do create a shell script that will do the following:

run only if specific files are found in a directory. If files are found, then I need to fix them by removing bad characters only from the file names. Wanted to replace these bad characters with a # so we can do a lookup for what the file should be renamed. This lookup is inside another file. I'm trying to learn perl, but have not used it much. Here's a better example(I hope)of what I'm stuck with.

Files come in as
Payroll(1000171)20090112_163013.xml

Add in the # so new file would be something like Payroll#1000171#20090112_163013.xml so then I could use
ls Payroll*.xml | awk -F# '{print $2}'to do the lookup on a text file for the correct field name.
#1000171# = 0218
Once I have this match I'm not sure how to grab the correct match name out so I end up with the following...
Payroll_0218_20090112.xml


Thanks!
4 REPLIES 4
Mark McDonald_2
Trusted Contributor

Re: shell script help

Just to clarify - you need to pull out what is in between the brackets and replace with another string.

Not sure but off the top of my head:

for FILE in `ls Payroll*.xml`
do
STRING=$(echo $FILE | awk -F"(" '{ print $2 }' | awk -F ")" '{ print $1 }')
#do the look up to get STRING2

$NEWFILENAME=#do some more awking as above to create this.
mv $FILE $NEWFILENAME
done

Saves putting the hashes in. Not sure whether the brackets should be quoted or escaped. You will have to experiment.
Mark McDonald_2
Trusted Contributor

Re: shell script help

Squeeze this in to the above loop:

$THEREST=4(echo $FILE|awk -F")" '{ print $2 }')
$NEWFILENAME="Payroll_"+$STRING2+"_"+$THEREST
Mark McDonald_2
Trusted Contributor

Re: shell script help

I wish we could edit posts!!!

If you struggle to awk for the brackets, try adding a "-b" option to the ls. This may print the octal value rather than the bracket. Again, give this ago, I am not in front of a unix box at present.
Dennis Handly
Acclaimed Contributor

Re: shell script help

Assuming your field mapping file "FIELD" looks like this:
1000181 = 0219
1000171 = 0218

And the number of files is small compared to records in FIELD.

ls Payroll\(*\)*.xml |
awk -F"[()]" -vFILE=FIELD '
{
s0 = $0
s1 = $1
s2 = $2
s3 = $3
save_FS = FS
FS = " "
stat = "grep \"" s2 "\" " FILE | getline
if (stat == 1)
print "mv \"" s0 "\"", s1 "_" $3 "_" s3
else
print "echo \"Cannot rename", $0 "\""
FS = save_FS
} '

This produces output like:
========================================================
mv "Payroll(1000171)20090112_163013.xml" Payroll_0218_20090112_163013.xml
mv "Payroll(1000181)20090112_163013.xml" Payroll_0219_20090112_163013.xml
echo "Cannot rename Payroll(1000191)20090112_163013.xml"

And then you can use a shell to execute the commands.