bash 将文件名分配给 shell 中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13519442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign file names to a variable in shell
提问by Zasito
I'm trying to write a script that does something a bit more sophisticated than what I'm going to show you, but I know that the problem is in this part.
我正在尝试编写一个脚本,它的功能比我要向您展示的要复杂一些,但我知道问题出在这一部分。
I want each name of a list of files in a directory to be assigned to a variable (the same variable, one at a time) through a for
loop, then do something inside of the loop with this, see what mean:
我希望通过for
循环将目录中文件列表的每个名称分配给一个变量(同一变量,一次一个),然后在循环内用这个做一些事情,看看是什么意思:
for thing in $(ls );
do
file $thing;
done
Edit: let's say this scrypt is called Scrypt and I have a folder named Folder, and it has 3 files inside named A,B,C. I want it to show me on the terminal when I write this:
编辑:假设这个 scrypt 叫做 Scrypt,我有一个名为 Folder 的文件夹,里面有 3 个文件,名为 A、B、C。当我写这个时,我希望它在终端上显示给我:
./scrypt Folder
the following:
下列:
A: file
B: file
C: file
With the code I've shown above, I get this:
使用我上面显示的代码,我得到了这个:
A: ERROR: cannot open `A' (No such file or directory)
B: ERROR: cannot open `B' (No such file or directory)
C: ERROR: cannot open `C' (No such file or directory)
that is the problem
那就是问题所在
采纳答案by Arkku
One way is to use wildcard expansion instead of ls
, e.g.,
一种方法是使用通配符扩展而不是ls
,例如,
for filename in ""/*; do
command "$filename"
done
This assumes that $1
is the path to a directory with files in it.
这假定这$1
是包含文件的目录的路径。
If you want to only operate on plain files, add a check right after do
along the lines of:
如果您只想对纯文件进行操作,请在do
以下行之后添加一个检查:
[ ! -f "$filename" ] && continue
回答by Master Chief
http://mywiki.wooledge.org/ParsingLs
http://mywiki.wooledge.org/ParsingLs
Use globbing instead:
改用通配符:
for filename in ""/* ; do
<cmd> "$filename"
done
Note the quotes around $filename
注意 $filename 周围的引号
回答by sampson-chen
It's a bit unclear what you are trying to accomplish, but you can essentially do the same thing with functionality that already exists with find
. For example, the following prints the contents of each file found in a folder:
有点不清楚您要完成什么,但是您基本上可以使用find
. 例如,以下打印文件夹中找到的每个文件的内容:
find FolderName -type f -maxdepth 1 -exec cat {} \;
回答by ofir.elhayani
well, i think that what you meant is that the loop will show the filenames in the desired dir. so, i would do it like that:
好吧,我认为您的意思是循环将在所需目录中显示文件名。所以,我会这样做:
for filename in ""/*; do
echo "file: $filename"
done
that way the result should be (in case in the dir are 3 files and the names are A B C:
这样结果应该是(如果目录中有 3 个文件并且名称是 ABC:
`file: A
`file: B
`file: C