Bash - 打印目录文件

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

Bash - Printing Directory Files

linuxbashshellunix

提问by theGrayFox

What's the best way to print all the files listed in a directory and the numer of files using a for loop? Is there a better of doing this?

使用 for 循环打印目录中列出的所有文件和文件数量的最佳方法是什么?有没有更好的做法?

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/"

for file in "$target"/*
do
  printf "%s\n" "$file" | cut -d"/" -f8
done

回答by Hai Vu

Here is a solution:

这是一个解决方案:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/"
let count=0
for f in "$target"/*
do
    echo $(basename $f)
    let count=count+1
done
echo ""
echo "Count: $count"

Solution 2

解决方案2

If you don't want to deal with parsing the path to get just the file names, another solution is to cdinto the directory in question, do your business, and cdback to where you were:

如果您不想处理解析路径以获取文件名,另一种解决方案是cd进入相关目录,做您的工作,然后cd回到您所在的位置:

#!/bin/bash

target="/home/personal/scripts/07_22_13/ford/"
pushd "$target" > /dev/null
let count=0
for f in *
do
    echo $f
    let count=count+1
done
popd
echo ""
echo "Count: $count"

The pushdand popdcommands will switch to a directory, then return.

pushdpopd命令将切换到一个目录,然后返回。

回答by theGrayFox

target="/home/personal/scripts/07_22_13/ford/"
for f in "$target"/*; do
    basename "$f"
done | awk 'END { printf("File count: %d", NR); } NF=NF'

basename "$f"will automatically output each filename on its own line, and the awk code will print the total number of records processed, which is this case is the number of files listed. Additionally, awk will automatically print the filenames because of the NF=NFpattern at the end. I'd say learning awk can be advantageous, as shown here. :-)

basename "$f"将自动在其自己的行上输出每个文件名,并且 awk 代码将打印处理的记录总数,这就是列出的文件数。此外,由于NF=NF末尾的模式,awk 将自动打印文件名。我想说学习 awk 可能是有利的,如下所示。:-)