4

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?

#!/bin/bash

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

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

2 回答 2

7

这是一个解决方案:

#!/bin/bash

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

解决方案 2

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

#!/bin/bash

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

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

于 2013-07-22T15:39:47.370 回答
0
target="/home/personal/scripts/07_22_13/ford/$1"
for f in "$target"/*; do
    basename "$f"
done | awk 'END { printf("File count: %d", NR); } NF=NF'

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

于 2013-07-22T21:25:15.017 回答