无法在shell脚本中使用带空格的文件名进行循环 [英] Can't take file names with spaces in shell script for loop

查看:34
本文介绍了无法在shell脚本中使用带空格的文件名进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带空格的文件名让它们进入 for 循环压缩每个文件压缩后,使用以下方法删除原件:

I am trying to take filenames with spaces Get them into a for loop zip each file Once zipped, remove the original using below:

for appdir in $(ls /home/location/$dirname); do

  for logFile in $(find /home/location/$dirname/$appdir -type f -mtime +10 \( ! -iname "*.zip" ! -iname "*.gz" \)); do
    echo $logFile

我试图压缩的文件有空格:

Files I am trying to zip which has spaces:

/home/location/hdd1/domain/servername/EXT1/ET SOME To FILENAME/xml/sdlfkd.xml
/home/location/hdd1/domain/servername/EXT1/ET SOME To FILENAME2/xml/sd2fkd.xml

我知道可以将带空格的文件名变成一个单独的文件名,如下所示 -

I know filenames with spaces can be made into a single filename like below -

find /location/$appdir -type f -mtime +10  -print0 | xargs -0 ls

从for"条件中获取文件名的实际 zi​​p 命令稍后会获取每个文件,制作一个 zip 文件并删除原始文件.

The actual zip command which takes the filename from the "for" condition comes later to take each file, makes a zip and removes the original one.

我收到以下 zip 命令错误:

I get below error for zip command:

[stdout: 4]                           zip warning: name not matched: ET
zip error: Nothing to do! (ET.zip)
[stdout: 4]           SOME
[stdout: 4]                           zip warning: name not matched: SOME
zip error: Nothing to do! (SOME.zip)

如何修改每次可以向for"循环提供整个文件名的条件,以便它继续压缩每个文件并进一步处理?任何帮助将不胜感激.

How can I modify the condition where I can provide entire filename each time to the "for" loop so it then proceeds to zip each file and goes further? Any help would be appreciated.

推荐答案

操作文件时始终使用双引号.

Always use double quotes when manipulating files.

例如,请参阅下面的代码将创建一个名为 a b c 的唯一文件:

See for example the code below will create one unique file called a b c :

will /home/will/a # touch "a b c"
will /home/will/a # ls -l
total 0
-rw-r--r--    1 root     system            0 Sep 21 08:47 a b c

但这将创建 3 个不同的文件,分别称为 a、b 和 c

But this will create 3 different files called, a, b and c

will /home/will/a # touch a b c
will /home/will/a # ls -l
total 0
-rw-r--r--    1 root     system            0 Sep 21 08:47 a
-rw-r--r--    1 root     system            0 Sep 21 08:47 b
-rw-r--r--    1 root     system            0 Sep 21 08:47 c

所以现在想象我不会创建而是删除或更改这些文件,如果文件名不是预期的,那可能会更有害.

So now imagine I would be not creating but deleting or altering those files, it could be much more harmful if files name were not the ones expected.

在你的情况下,我会试试这个:

In your case I would try this :

   for appdir in $(ls "/home/location/$dirname"); do

  for logFile in $(find "/home/location/$dirname/$appdir" -type f -mtime +10 \( ! -iname "*.zip" ! -iname "*.gz" \)); do
    echo "$logFile"

这篇关于无法在shell脚本中使用带空格的文件名进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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