Well i am really pissed off :(
I have a file called test.txt. and here it is:
"/var/lib/backup.log"
"/var/lib/backup2.log"
double quotes are included in the file each at beginning and end of the directory and i can not remove them.
i am trying to write a script to remove files in test.txt.
like this:
for del in `cat test.txt` ; do
rm -f $del
done
but it does not work as expected :(
it gives this error:
rm: cannot access "/var/lib/backup.log": No such file or directory
rm: cannot access "/var/lib/backup.log2": No such file or directory
This will just remove the quote character from the beginning and the end of the read entry, which is better than blindly removing all quote characters (since they can appear in filenames, of course).
And, regarding your initial code, PLEASE ALWAYS USE QUOTES until you really know when and when not.
while read -r; do
fname=${REPLY#\"}
fname=${fname%\"}
echo rm -f "$fname"
done < myfiles.txt
The following one-liner should do it:
rm $(tr '\"' '\0' < test.txt)
Here, tr
translates all "
to null (\0
), where the input is from the file named test.txt
. Finally, rm
is supplied with the results.
The following Perl one-liner can be used for the same too:
perl -nle 's{"}{}g;unlink' test.txt
Searches and replaces "
from the each line read from test.txt
. Then, unlink
removes the file.
Or,
sed 's! !\\ !g' < test.txt | sed 's/"//g' | xargs rm
Escape spaces, remove "
and delete the file.
It's easy to rustle up a quick Perl script
#!/bin/perl
while (<STDIN>) {
chomp;
s/"//g;
unlink $_;
}
and run it thus:
./script.pl < test.txt
Although you've specified bash in the above, I'm not sure if you really want a bash-only solution.
Note that this will handle whitespaces in file names etc.
I guess eval
command will do that work for you:
for del in `cat test.txt` ; do
eval rm -f $del
done