views:

657

answers:

4

Hi everyone. 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
+2  A: 

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.

Alan Haggai Alavi
It might be useful to explain the above for the uninitiated :-)
Brian Agnew
@Brian Agnew: I have done so. :-)
Alan Haggai Alavi
Why turn quotes into nulls? Why not just delete quotes with tr -d
camh
A: 

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.

Brian Agnew
+1  A: 

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
TheBonsai
A: 
rm $(cat this-file)

Double quotes will be interpreted by shell and removed. Depending on the contents of the file, it might be the simplest solution...

liori
This is just wrong.
TheBonsai