linux - 脚本不保存新行或计算文件大小的问题

标签 linux shell scripting

我注意到我的脚本存在问题。这里的大问题来 self 的 fprintf 没有将换行符正确保存到文件中。例如,当我使用特定的测试文件时,应该有 47 个新行被保存。我已经单独尝试了 find 命令并将其通过管道传输到 wc -l 以获取数字。但是,当我尝试保存到一个文件(为每个结果保存一个新行并尝试对其进行计数)时,我只得到 35。对我来说奇怪的是,当我交换文件扩展名的顺序时(搜索gif first 例如)它也会混淆保存的新行(首先做 gif 保存 3 行)。所以我不确定那里有什么交易。

我遇到的另一个问题是打印出正确的文件大小。例如,在我使用的一个测试文件中,我的总文件大小为 2,908,160,而它应该是 2,628,419。

这是我的脚本:

#!/bin/bash
#Godfried Weihs
#Lab 2 - Search and Report
#CS 3030 - Scripting

#If Statement checks for usage, prints appropriate message if path is empty
#+ else it runs through the scripts normally

if [ -z "$1" ]; then
    echo Usage: srpt path
    exit 1
else
    echo -e "SearchReport $HOSTNAME $(basename "$1") $(date)\n"

    #Finds all required files and saves them to temporary files to be used for count output
    find $1 -mindepth 1 \
    \( -type d -fprintf /tmp/dcnt "\n" \) , \
    \( -type f -fprintf /tmp/fcnt "\n" \) , \
    \( -type l -fprintf /tmp/scnt "\n" \) , \
    \( -type f -mtime +365 -fprintf /tmp/ocnt "\n" \) , \
    \( -type f -size +500000c -fprintf /tmp/lcnt "\n" \) , \
    \( -type f -name *.jpg -o -name *.bmp -o -name *.gif -fprintf /tmp/gcnt "\n" \) , \
    \( -type f -name '*.o' -fprintf /tmp/tcnt "\n" \) , \
    \( -type f -executable -fprintf /tmp/ecnt "\n" \) , \
    \( -type f -fprintf /tmp/total "$(du -ch -B1 $1)" \)

    #Print out results saved in tmp folder
    echo Execution time $SECONDS
    printf "Directories %'d\n"  $(cat /tmp/dcnt | wc -l)
    printf "Files %'d\n" $(cat /tmp/fcnt | wc -l)
    printf "Sym links %'d\n" $(cat /tmp/scnt | wc -l)
    printf "Old files %'d\n" $(cat /tmp/ocnt | wc -l)
    printf "Large files %'d\n" $(cat /tmp/lcnt | wc -l)
    printf "Graphics files %'d\n" $(cat /tmp/gcnt | wc -l)
    printf "Temporary files %'d\n" $(cat /tmp/tcnt | wc -l)
    printf "Executable files %'d\n" $(cat /tmp/ecnt | wc -l)
    #printf "Total file size %'d\n" $(du -hs -B1 $1 | cut f -1)     
    #printf "Total file size %'d\n" $(du -ch -B1 $1 | tail -n1 | cut -f 1)
    printf "Total file size %'d\n" $(cat /tmp/total | tail -n1 | cut -f 1)

fi

我觉得有几件小事我只是没有看到。任何帮助将不胜感激。

最佳答案

用图像文件扩展名引用参数,否则通配符将被 shell 扩展而不是传递给 find(除非当前目录中没有匹配的文件)。此外,您需要将它们全部用括号组合在一起,因为 -o 的优先级低于组合相邻表达式的隐含 -a;这就是扩展顺序很重要的原因,您只为最后一个表达式运行 -fprintf

\( -type f \( -name '*.jpg' -o -name '*.bmp' -o -name '*.gif' \) -fprintf /tmp/gcnt "\n" \) , \

关于总文件大小,du 获取每个文件的大小(以磁盘 block 为单位),而不是文件长度(以字节为单位)。因此,报告的总长度将大于所有文件的总长度,因为它们都四舍五入到下一个 block 大小。

关于linux - 脚本不保存新行或计算文件大小的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41599009/

相关文章:

linux - 差异工具中的 1c1 是什么意思?

bash - 如何使用 shell 命令一次创建指向多个目录的符号链接(symbolic link)

PHP Shell_Exec 不工作?

linux - ssh 如何从 tty 接收密码?

c - 如何检查路径是否指定卷根目录

git:仅暂存新文件

linux - 如何将输出存储到日志而不是回显

linux - 如何打印随机行的列

shell - 如何导致 Linux 管道失败?

shell - 如何使用 grep 命令确定字符串是否包含换行符?