linux - 计算 shell 脚本中文件的中等行数

标签 linux shell

我必须编写一个 shell 脚本,该脚本采用一个目录的名称,然后搜索该目录和所有子目录中的所有文件,并计算中间行数。 这是我尝试过的:

#!/bin/sh

if [ $# -eq 0 ] #  check if a directory was pass as argument 
then
    echo "The call requires a directory name ! ";
    exit 1
fi

dirname=$1  # save the directory name
if [ ! -d $dirname ]  # check if it is a valid directory 
then
    echo $dirname is not a directory
    exit 1
fi

files_number=0    # the total number of files
files_lines_nr=0  # the total number of lines of the files

for fis in ` find $dirname -type f ` # loops the files in all the directories
do
    lines=` wc -l <$fis ` # get the number of lines in a file
    files_number=` expr $files_number + 1 ` # counts the number of files
    files_lines_nr=` expr $files_lines_nr + $lines ` # updates the total number of lines
done
echo "The medium number of lines :" ` expr $files_lines_nr / $files_number ` 

如果我通过具有 1 个文件 test3 和 1 个子目录的 drectory hw1 -> 包含 test2 和 test1 文件,我得到值 7(文件 test2 中的行数)两次。我做了一些 echo ,结果如下:

0  in file tema1/test1~ 
0  in file tema1/test3~ 
7  in file tema1/subhw1/test2~  //why ?
7  in file tema1/subhw1/test2  // correct number of lines
11  in file tema1/test3  // correct number of lines
5  in file tema1/test1  // correct number of lines
Total number of lines :30  // incorect computes 7 twice
The medium number of lines : 5 // incorect there are only 3 files ,he counts 6.

谢谢!

最佳答案

由于 ~ 文件会在您单击编辑器中的“保存”按钮时返回,您可能需要考虑系统地排除它们,而不是简单地删除现在存在的文件。这样你的 shell 脚本会随着时间的推移变得更有用。您可以使用 find 命令执行此操作。这是一个例子:

find . -type f -and \( -name "*~" -prune -or -print \)

它说有两件事必须是真的:它必须是一个常规文件,并且它必须以 ~ 结尾,在这种情况下 find 将修剪 结果(即不打印),或者打印出来。

可读性稍差的 POSIX 兼容版本是:

find . -type f \( -name "*~" -prune -o -print \)

但是,不同的编辑器对临时/备份文件的命名方案不同。 Vim 使用 .filename.swp,Emacs 使用 #filename#,GEdit 使用 filename~ 等等。对于真正通用的脚本,您可能还需要考虑支持这些脚本:

find . -type f \( -name "*~" -prune -o \
                  -name "*#" -prune -o \
                  -name "*.swp" -prune -o -print \)

关于linux - 计算 shell 脚本中文件的中等行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23592513/

相关文章:

linux - printf 中的汇编程序段错误

linux - 在 golang 中写在热敏打印机设备上

linux - 为什么 "while"并发在 shell 脚本中运行越来越慢?

ruby - ruby 和 shell 之间不同的 sudo 环境变量

linux - 创建init.d脚本文件

linux - 'sort' 核心实用程序的 key (-k) 语法背后的推理

linux - TCP内核实现

Linux Buddy 页框分配和释放

linux - Bash - 为我在猫?

linux - 基于列,文件 1 中的行不存在于文件 2 中