当文件名包含空格时查找单独的文件名(Shell) [英] Find separates filenames when they contain a space (Shell)

查看:83
本文介绍了当文件名包含空格时查找单独的文件名(Shell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我的程序旨在循环浏览目录及其子目录,并在找到大于100K的文件时询问用户是否要删除该文件.

So, my program is meant to cycle through a directory and its subdirectories, and when it finds a file that is larger than 100K, asks the user if they want to remove it.

我正在使用find循环浏览目录.这是我的代码:

I am using find to cycle through the directories. This is my code:

for file in $(find /home/* -print0 | xargs -0)

我也尝试过

for file in $(find /home/* -exec process)

等等.Google前五页中的几乎所有内容.

Etc, etc. Pretty much everything on the first five pages of Google.

只是要重申一下,问题是查找使用分隔的文件名分隔文件名.(即"/home/Old data"将变为"/home/Old"和"data"

Just to re-iterate, the problem is that find separates filenames with spaces in them. (i.e. "/home/Old data" would become "/home/Old" and "data"

反正我还有其他更好的选择吗?

Anyway, are there any better alternatives that I could be using?

推荐答案

不使用进程替换 $(...),因此所有文件名都以一行显示,并以空格.然后无法分辨文件名中的空格和分隔符.但是,如果用"$(...)" 引用,则所有输出都将显示为单个多行字符串.因此,通过这种方式将命令输出传递到 for 循环是行不通的.而是使用 xargs 进行工作.

The process substitution $(...) isn't quoted, so all the filenames come out on one line, separated by spaces. There's no way then to tell which spaces are in filenames and which are separators. But if you quote it, "$(...)", then all the output comes out as a single multi-line string. So doing it this way, passing the command output to a for loop, doesn't work. Instead, use the xargs to do the work.

find /home/* -print0 | xargs -0 -i{} ls -l {}

这与您的 find | xargs 完全一样,只是给 xargs 提供了要执行的命令.在您的情况下,它将是文件中的Shell脚本,例如 mayberemove.sh .通常, xargs 会将尽可能多的输入行附加到命令的末尾,但是 -i 告诉它使用输入行代替(任意)字符串 {} .在这种情况下,一次只能使用一条输入线.因为 xargs 不会通过外壳传递参数,而是使用各种 exec 来运行命令,所以不再需要引用. -0 表示参数由 find -print0 输出的空字节定界,以避免出现空格问题.

This works exactly like your find|xargs except that the xargs is given a command to execute. In your case it will be a shell script in a file, e.g. mayberemove.sh. Normally xargs appends as many input lines onto the end of the command as it can, but the -i tells it to run the command with the input line in place of the (arbitrary) string {}. In this case it only uses one input line at a time. Because xargs isn't passing the argument through a shell, but instead runs the command using some variety of exec, there's no need for any more quoting. The -0 means that the arguments are delimited by a null byte, as output by find -print0, to avoid problems with whitespace.

您将需要以下内容,而不是 ls -l <​​/code>:

Instead of ls -l, you will want something like:

find /home/* -print0 | xargs -0 -i{} ./mayberemove.sh

其中 mayberemove.sh 谨慎地引用其参数,因为它正在使用外壳传递它们:

where mayberemove.sh is careful to quote its arguments, because it is passing them using the shell:

#!/bin/sh

if ....
then
    rm "$1"
fi

这篇关于当文件名包含空格时查找单独的文件名(Shell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆