遍历路径中带有空格的文件名 [英] Loop through filenames with spaces within a path

查看:65
本文介绍了遍历路径中带有空格的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将路径名传递给脚本,但是我的路径包含空格(例如/Users/netto/iTunes \ Media/Music/).我尝试将实际路径直接放在for循环中,并且能够获取所有文件.不幸的是,我无法将其作为变量传递.我已经尝试了双引号和单引号.这是我目前所拥有的

I wanted to pass the path name to the script, but my path has spaces (eg. /Users/netto/iTunes \Media/Music/). I have tried putting the actual path directly on the for loop, and I was able to get all the files. Unfortunately, I could not pass it as variable. I have tried both double quote, and single quote. This is what I have currently

$PATH=$1
for f in $PATH; do
   echo "Processing file $f " 
done

请让我知道如何执行此操作.预先谢谢你.

Please let me know on how to do this. Thank you in advance.

推荐答案

在命令级别扩展变量中的空格,因此要解决此问题,可以在"$ 1"前后加上引号(以便正确转义空格)或使用bash数组.

Spaces in variables are expanded at command level, so to solve the problem you can either put quotation marks around "$1" (so spaces are properly escaped) or use bash arrays.

这是两个应该起作用的示例:

Here is two example that should work:

 #!/bin/bash
DIR="$1"
for f in "$DIR"/* 
do
  echo "Processing file $f " 
done

或使用bash数组:

#!/bin/bash
FILES=("$1"*)
for f in "${FILES[@]}"
do
  echo "Processing file $f " 
done

这篇关于遍历路径中带有空格的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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