如何在不使用通配符的情况下遍历 unix 目录的内容?
How can I iterate over the contents of a directory in unix without using a 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
没关系。但是我找不到任何方法在不使用该通配符的情况下迭代这些图像。
我不想使用通配符。仅有的文件以 'dog' 或 'cat' 为前缀。我不需要匹配。所有文件都是 .jpg。
我不能不使用通配符而只遍历目录的内容吗?我知道这是一个 XY 问题,但我仍然想学习这个。
当没有匹配的文件时,*.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
我完全明白问题出在哪里了。
我有一组文件,前缀为 '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
没关系。但是我找不到任何方法在不使用该通配符的情况下迭代这些图像。
我不想使用通配符。仅有的文件以 'dog' 或 'cat' 为前缀。我不需要匹配。所有文件都是 .jpg。
我不能不使用通配符而只遍历目录的内容吗?我知道这是一个 XY 问题,但我仍然想学习这个。
*.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