简体   繁体   English

Bash - 遍历文件,排除目录

[英]Bash - iterate over files, exclude directories

I'm trying to rename files in a directory to lowercase.我正在尝试将目录中的文件重命名为小写。 I need to loop through their names.我需要遍历他们的名字。 I tried:我试过:

for i in *;

But this iterates over files and directories.但这会遍历文件目录。 How do I make it, so that it only iterates through the files?我如何制作它,以便它只遍历文件?

Test if it is a file, and then do your command.测试它是否是一个文件,然后执行您的命令。 If it isn't a file, the && will short circuit and the second part will not be executed.如果不是文件, &&会短路,第二部分不会被执行。

for i in *; do [[ -f "$i" ]] && echo "$i"; done

Years after the answer from Doon, I found an (arguably) nicer solution, based on this Ask Ubuntu answer .在 Doon 给出答案多年后,我找到了一个(可以说)更好的解决方案,基于这个 Ask Ubuntu answer It does not require any test inside the body of the loop:它不需要在循环体内进行任何测试:

for fn in $(ls -p | grep -v /); do echo $fn; done
  • ls -p will list out contents of the current directory, with / appended to directory names ls -p将列出当前目录的内容,将/附加到目录名称
  • grep -v / will filter the output, removing lines with / grep -v /将过滤输出,删除带有/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM