如何使用 awk 或 bash 打印文件夹中的所有文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12462625/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:17:47  来源:igfitidea点击:

How to print all file names in a folder with awk or bash?

bashawk

提问by lara

I would like to print all file names in a folder.How can I do this with awk or bash?

我想打印文件夹中的所有文件名。如何使用 awk 或 bash 执行此操作?

回答by Ashish Kumar

ls -l /usr/bin | awk '{ print $NF }' 

:)

:)

回答by xception

find . -type f -maxdepth 1

exclude the -maxdepth part if you want to also do it recursively for subdirectories

如果您还想对子目录递归执行此操作,请排除 -maxdepth 部分

回答by Tomasz Skorka

Following is a pure-AWK option:

以下是纯 AWK 选项:

gawk '
    BEGINFILE {
        print "Processing " FILENAME
    };
' *

It may be helpful if you want to use it as part of a bigger AWK script processing multiple files and you want to log which file is currently being processed.

如果您想将其用作处理多个文件的更大 AWK 脚本的一部分,并且您想记录当前正在处理的文件,这可能会有所帮助。

回答by Rashedul Islam

This command will print all the file names:

此命令将打印所有文件名:

for f in *; do echo "$f"; done

or (even shorter)

或(甚至更短)

printf '%s\n' *

Alternatively, if you like to print specific file types (e.g., .txt), you can try this:

或者,如果您想打印特定文件类型(例如,.txt),您可以尝试以下操作:

for f in *.txt; do echo "$f"; done

or (even shorter)

或(甚至更短)

printf '%s\n' *.txt

回答by BjoernD

/bin/ls does this job for you and you may call it from bash.

/bin/ls 为您完成这项工作,您可以从 bash 调用它。

$> /bin/ls
[.. List of files..]

Interpreting your question you might be interested in iterating over every single file in this directory. This can be done using bash as well:

解释您的问题,您可能有兴趣遍历此目录中的每个文件。这也可以使用 bash 来完成:

for f in `ls`; do
   echo $f;
done

回答by Vaishnavi Varma

for f in *; do var=`find "$f" | wc -l`; echo "$f: $var"; done

This will print name of the directory and number of files in it. wc -lhere returns count of files +1 (Including directory)

这将打印目录的名称和其中的文件数。wc -l这里返回文件数+1(包括目录)

Sample output:

示例输出:

aa: 4 
bb: 4 
cc: 1 
test2.sh: 1