如何使用bash做一些事来的每一个文件的目录中? [英] How to do something to every file in a directory using bash?
问题描述
我开始用这样的:
command *
但是,当该目录为空它不工作;通配符*变成文字*字符。所以,我切换到这一点:
But it doesn't work when the directory is empty; the * wildcard becomes a literal "*" character. So I switched to this:
for i in *; do
...
done
这工作,但同样,如果没有该目录是空的。我使出使用LS:
which works, but again, not if the directory is empty. I resorted to using ls:
for i in `ls -A`
但当然,然后在他们的空间得到拆分的文件名。我试着套结了-Q开关:
but of course, then file names with spaces in them get split. I tried tacking on the -Q switch:
for i in `ls -AQ`
这将导致仍然被分割的名字,只在开头一个引号字符,名称的结束。我失去了一些东西在这里很明显,或者是这个难度比它它应该是什么?
which causes the names to still be split, only with a quote character at the beginning and ending of the name. Am I missing something obvious here, or is this harder than it ought it be?
推荐答案
假设你只想做一些事来的文件,简单的解决方案是测试如果$ i是一个文件:
Assuming you only want to do something to files, the simple solution is to test if $i is a file:
for i in *
do
if test -f "$i"
then
echo "Doing somthing to $i"
fi
done
您真的应该总是做这样的测试,因为你几乎肯定不希望把以同样的方式文件和目录。注意哪些美元,包含空格的文件名p $ pvent问题,围绕$ i的引号。
You should really always make such tests, because you almost certainly don't want to treat files and directories in the same way. Note the quotes around the "$i" which prevent problems with filenames containing spaces.
这篇关于如何使用bash做一些事来的每一个文件的目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!