Link to home
Start Free TrialLog in
Avatar of mohona
mohona

asked on

Script for removing characters in files

Dear Experts,

1.I need a script which will search a directory for files which contains " inside files (not in filenames) and remove this character(")from that file.

2. IT will also log everything to a log file with execution time and date.

Please help me.

Thanks,
Mohona.
 
Avatar of edster9999
edster9999
Flag of Ireland image

The command is :

for i in `grep -l "\"" *`; do echo "updated - $i"; mv $i $i.bak ; cat $i.bak | tr -d "\"" > $i ; done

This will look for double quote in all files. (Change to *.txt if you want to narrow it down)

All files it finds are then moved to filename.bak and then stripped of the double quote and saved with the original name.

or as a script file :


#!/bin/bash
 
logfile="/var/logs/strip.log"
 
echo "Strip executed `date`" >> $logfile
 
for i in `grep -l "\"" *`; do 
    echo "updated - $i" >> $logfile
    mv $i $i.bak  
    cat $i.bak | tr -d "\"" > $i 
done

Open in new window

Avatar of mohona
mohona

ASKER

but how do I mention the directory, or shall i run it from the directory where I need to search for files?

This would work on the current directory you were in so you could put it somewhere on the path like
/usr/bin/
and then as you move round you could run it.

Or if you want to specify it you could do something like :


#!/bin/bash
 
logfile="/var/logs/strip.log"
 
echo "Strip executed `date`" >> $logfile
 
if [ $# -ne 1 ]; then
        echo "Please put the directory name after the command"
        echo "Stopped due to wrong parameters" >> $logfile
else
    for i in `grep -l "\"" $1/*`; do 
        echo "updated - $i" >> $logfile
        mv $i $i.bak  
        cat $i.bak | tr -d "\"" > $i 
    done
fi

Open in new window

and you could add in this line
    echo "on this directory - $1" >> $logfile
after the else before the for line
so it logs the directory name too.

Now this doesn't check the syntax of the directory line you give it so if you put something silly on the line you will prob get nothing back
Avatar of mohona

ASKER

Thank you, almost completed and woking very nice.
One last thing is that, I don't want to pass the directory name as an argument. Please make it permanent like example /data/abc/xyz .  
ASKER CERTIFIED SOLUTION
Avatar of edster9999
edster9999
Flag of Ireland image

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
Avatar of mohona

ASKER

Excellent! Thank you.
Avatar of Tintin
Huh?  This is the *exact* same question asked a few days ago (which was answered).  Is this a duplicate or an assignment question?
Whoops.  I didn't see the link to the related question and didn't read this one carefully enough.  Sorry.