如何在不使用通配符的情况下迭代unix中目录的内容?

时间:2017-05-16 21:11:12

标签: bash unix wildcard

我完全明白这里的问题是什么。

我有一组文件,前缀为' cat.jpg'和' dog.jpg。'我只是想移动'cat.jpg'将文件放入名为' cat。'的目录中。与' dog.jpg'相同文件。

for f in *.jpg; do
    name=`echo "$f"|sed 's/ -.*//'`
    firstThreeLetters=`echo "$name"|cut -c 1-3`
    dir="path/$firstThreeLetters"
    mv "$f" "$dir"
done

我收到此消息:

mv: cannot stat '*.jpg': No such file or directory

没关系。但我无法在不使用该通配符的情况下找到迭代这些图像的方法。

我不想使用通配符。唯一的文件以“狗”为前缀。或者' cat'。我不需要匹配。所有文件都是.jpgs。

我不能在不使用通配符的情况下迭代目录的内容吗?我知道这是一个XY问题,但我仍然希望了解这一点。

1 个答案:

答案 0 :(得分:3)

当没有匹配的文件时,

*.jpg会产生文字*.jpg。 看起来您需要nullglob。使用Bash,您可以这样做:

#!/bin/bash

shopt -s nullglob                # makes glob expand to nothing in case there are no matching files
for f in cat*.jpg dog*.jpg; do   # pick only cat & dog files
  first3=${f:0:3}                # grab first 3 characters of filename
  [[ -d "$first3" ]] || continue # skip if there is no such dir
  mv "$f" "$first3/$f"           # move
done