linux - Basename 带空格的文件名,并在命令 1 中使用带空格的文件名

标签 linux bash shell command-line scripting

我是 shell 脚本新手,遇到了一些问题。我不知道如何将文件名保存在变量中并在命令中使用它们。

我正在尝试查找特定扩展名的文件路径,然后保存

  1. 文件名

在 $name 变量中并使用信息运行识别来检查图像的宽度和高度。

对于基于下面代码的错误,我得到

  1. 识别:无法打开图像 ~/PATH/name
  2. 识别:无法打开图像./with
  3. 识别:无法打开图像./spaces

如果我执行 echo $name 来检查名称是否正确保存,我会得到

  1. 姓名
  2. spaces.jpg

该命令有什么方法可以获取带有空格的完整文件名吗?简单地双引号变量似乎没有帮助。

(我已经用双引号完成了 name=$(basename "$a") 。还有 width=$(identify $a | cut -d ' ' -f 3 | cut -d 'x' -f 1 ) 也不起作用)

for a in `find "$dir" -type f \( -iname "*.jpg" -o -iname "*.jpeg" \)`;do
    name=$(basename "$a")

    directory=$(dirname "$a")
    #echo "$name"
    width=$(identify "$directory/$name" | cut -d ' ' -f 3 | cut -d 'x' -f 1 )
    height=$(identify "$directory/$name" | cut -d ' ' -f 3 | cut -d 'x' -f 2 )

最佳答案

或者,您可以使用 while read 代替 for 循环:

find $directory -type f \( -iname "*.jpg" -o -iname "*.jpeg" \) |
while read a
do

无论您如何操作,还需要在 identify 命令中处理空格 - 正如您所看到的那样,以空格分隔的字段的剪切将无法正常工作。我建议:

    let `identify -format "width=%w height=%h" "$directory/$name"`

关于linux - Basename 带空格的文件名,并在命令 1 中使用带空格的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75530113/

相关文章:

c++ - 如何找到我的进程在 Linux 中打开的文件句柄?

linux - 如何在bash中对一系列数字求和

linux - 如何在 xfs 中获取文件创建日期/时间

ios - Xcode-命令行构建

shell - 测试远程 TCP 端口是否从 shell 脚本打开

linux - 如何求从命令行输入的数字的平均值

linux - 未找到 Bash 脚本,尽管它在 $PATH 中

linux - 需要将带有图像的子目录的目录转换为 webp

linux - 使用 netcat (nc) 作为 HTTP 代理服务器和监视器

Bash 脚本 : Printing a column with having space between the string