猛砸,遍历目录 [英] Bash, looping over directories

查看:114
本文介绍了猛砸,遍历目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何bash的作品一个根本性的问题,和相关的实践问题。

I have a fundamental question about how bash works, and a related practical question.

最基本的问题:假设我是有三个子目录的目录:A,B和C

Fundamental question: suppose I am in a directory that has three subdirectories: a, b, and c.

母鸡code

for dir in $(ls)
do 
    echo $dir
done

吐出:

a b c
a b c
a b c

即, DIR 总是存储在我的 CWD 所有的文件/目录的列表。我的问题是:为什么在世界上会变成这样方便?在我看来,这是更为有用的,直观的让 DIR 存储每次打开一个元素,即我希望有输出

i.e, dir always stores a list of all of the files/directories in my cwd. My question is: why in the world would this be convenient? In my opinion it is far more useful and intuitive to have dir store each element at a time, i.e I would want to have output

a
b
c

此外,作为每一个答案 - 这是错误的使用在$(LS)DIR ,但是当我使用为DIR在$(ls -l命令)我得到 ABC 更显副本(以上有目录/在CWD文件)。这是为什么?

Also, as per one of the answers - it is wrong to use for dir in $(ls), but when I use for dir in $(ls -l) I get even more copies of a b c (more than there are directories/files in the cwd). Why is that?

我的第二个问题是实用:在我的我怎么遍历所有目录(而不是文件!)CWD 与资本W¯¯开始?我开始用

My second question is practical: how do I loop over all the directories (not files!) in my cwd that start with capital W? I started with

for dir in `ls -l W*`

但这种失败,因为一)问题的原因1和b),因为它不排除文件。建议AP preciated。

but this fails because a) the reason in question 1 and b) because it doesn't exclude files. Suggestions appreciated.

推荐答案

永远不要解析 LS的输出像这样(的为什么你不应该解析ls的输出结果(1))。

Never ever parse the output of ls like this (Why you shouldn't parse the output of ls(1)).

另外,你的语法是错误的。你不是说(),你的意思是 $()

Also, your syntax is wrong. You don't mean (), you mean $().

话虽这么说,遍历目录,开始用W,你会做(或使用找到命令来代替,这取决于您的方案):

That being said, to loop over directories starting with W you would do (or use the find command instead, depending on your scenario):

for path in /my/path/W*; do
    [ -d "${path}" ] || continue # if not a directory, skip
    dirname="$(basename "${path}")"
    do_stuff
done

至于你从邪恶的LS-循环得到的输出,它不应该像她那样。这是预期的输出,并演示了为什么你不希望在第一时间使用LS:

As for the output you get from the evil ls-loop, it should not look like that. This is the expected output and demonstrates why you do not want to use ls in the first place:

$ find
.
./c
./a
./foo bar
./b

$ type ls
ls is hashed (/bin/ls)

$ for x in $(ls); do echo "${x}"; done
a
b
c
foo
bar

这篇关于猛砸,遍历目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆