how to delete a file with quote in file name

2019-09-11 07:56发布

When I do ls in my directory, get bunch of these :

data.log".2015-01-22"
data.log".2015-01-23"

However when I do this :

rm: cannot remove `data.log.2015-01-22': No such file or directory

If I could somehow do something line ls | escape quotes | xargs rm

So yeah, how do I remove these files containing "?

Update

While most answer work. I was actually trying to do this :

ls | rm

So it was failing for some files. How can I escape quote in pipe after ls. Most of the answers actually addresses the manual manipulation of file which works. But I was asking about the escaping/replacing quotes after the ls. Sorry if my question was confusing

标签: bash shell
6条回答
啃猪蹄的小仙女
2楼-- · 2019-09-11 08:25

Use single quotes to quote the double quotes, or backslash:

rm data.log'"'*
rm data.log\"*

Otherwise, double quotes are interpreted by the shell and removed from the string.

Answer to the updated question:

Don't process the output of ls. Filenames can contain spaces, newlines, etc.

查看更多
相关推荐>>
3楼-- · 2019-09-11 08:32

1st - suggestion - modify the tool creating file names with quotes in them... :)

Try a little wild-char magic - using your tool of choice, i.e I would use tr:

ls | escape quotes | xargs rm  ## becomes something like:  
ls | tr "[\",']" '?' | xargs rm ## does not work on my system but this does:
rm -v $(ls *sing* *doub* | tr "[\",']" '?')

Output is:

removed `"""double"""'
removed `\'\'\'single\'\'\''

Now:

$ touch "'''single'''" '"""double"""'
$ ls -l *sing* *doub*
-rw-rw-r-- 1 dale dale 0 Feb 15 09:48 """double"""
-rw-rw-r-- 1 dale dale 0 Feb 15 09:48 '''single'''

If your patterns are consistent the other way might be to simplify:

$ rm -v *sing* *doub*
removed `\'\'\'single\'\'\''
removed `"""double"""'

For your example:

rm -v data.*${YEAR}-${MONTH}-${DAY}*  ## data.log".2015-01-22"  OR
rm -v data.*${YEAR}-${MONTH}-${DAY}?  ## data.log".2015-01-22"
查看更多
我想做一个坏孩纸
4楼-- · 2019-09-11 08:33
ls | rm

doesn't work because rm gets the files to remove from the command line arguments, not from standard input. You can use xargs to translate standard input to arguments.

ls | xargs -d '\n' rm

But to just delete the files you want, quote the part of the name containing the single quote:

rm 'data.log"'.*
查看更多
戒情不戒烟
5楼-- · 2019-09-11 08:39

If you only need to do this once in a while interactively, use

rm -i -- *

and answer y or n as appropriate. This can be used to get rid of many files having funny characters in their name.

查看更多
一纸荒年 Trace。
6楼-- · 2019-09-11 08:45

You could do like this.

find . -type f -name '*"*' -exec rm {} +
查看更多
Explosion°爆炸
7楼-- · 2019-09-11 08:46

Escape the quote with single quotes

$ touch '"  and spaces also "'
$ ls
"  and spaces also "
$ rm '"  and spaces also "'
$ ls
$

In your case:

$ rm 'data.log".2015-01-22"' 'data.log".2015-01-23"'
查看更多
登录 后发表回答