Simple bash script to read from one file having do

2019-08-27 20:02发布

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

4条回答
虎瘦雄心在
2楼-- · 2019-08-27 20:41

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.

查看更多
beautiful°
3楼-- · 2019-08-27 20:42

I guess eval command will do that work for you:

for del in `cat test.txt` ; do
  eval rm -f $del
done
查看更多
别忘想泡老子
4楼-- · 2019-08-27 20:48

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
查看更多
冷血范
5楼-- · 2019-08-27 20:50

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.

查看更多
登录 后发表回答