Bash确定文件大小 [英] Bash to determine file size

查看:150
本文介绍了Bash确定文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还在学习bash,但我对我的剧本有一些疑问。

Still learning bash but I had some questions in regards to my script.

我的目标是使用jpg图像访问文件夹,如果图像是34.9kb它将返回文件不存在。 34.9kb是显示图像不存在的图像大小。

My goal with the script is to access a folder with jpg images and if an image is 34.9kb it will return file not present. 34.9kb is the size of the image that shows "image not present".

#!/bin/bash

#Location
DIR="/mnt/windows/images"

file=file.jpg
badfile=12345
actualsize=$(du -b "$file" | cut -f 1)
if [ $actualsize -ge $badfile ]; then
    echo $file does not exist >> results.txt
else
    echo $file exists >> results.txt
fi

我需要它将每行打印到名为results的txt文件。我做过研究,有人建议使用 du -b stat -c'%s'但是我不能看看使用其中一个的利弊是什么。打印文件是否会在if else之后或者保留为if,因为Im打印每个文件?我需要在同一行打印名称和结果。回复文件的最佳方法是什么?

I need it to print each line to a txt file named results. I did research where some people either suggested using du -b or stat -c '%s' but I could not see what the pros and cons would be for using one or the other. Would the print to file come after the if else or stay with the if since Im printing for each file?? I need to print the name and result in the same line. What would be the best way to echo the file??

推荐答案

根据您的问题和对你的下一个问题我假设你想做的是:

Based on your question and your comments on your following question I'm assuming what you want to do is:


  1. 遍历特定目录中的所有* .jpg文件

  2. 根据图像大小运行不同的命令


    • 具体来说,如果文件大小为40318字节,则要打印[filename]不存在

  1. Iterate through all the *.jpg files in a specific directory
  2. Run different commands depending on the size of the image
    • Specifically, you want to print "[filename] does not exist" if the file is of size 40318 bytes.

如果我的假设很接近,那么这应该让你开始:

If my assumptions are close, then this should get you started:

# Location
DIR="/home/lsc"
# Size to match
BADSIZE=40318

find "$DIR" -maxdepth 1 -name "*.jpg" | while read filename; do
    FILESIZE=$(stat -c "%s" "$filename")  # get file size
    if [ $FILESIZE -eq $BADSIZE ]; then
        echo "$filename has a size that matches BADSIZE"
    else
        echo "$filename is fine"
    fi
done

请注意,我已使用 find ... | while read filename 而不是 for * in .jpg ,因为前者可以更好地处理包含空格的路径。

Note that I've used "find ... | while read filename" instead of "for filename in *.jpg" because the former can better handle paths that contain spaces.

请注意 $ filename 将包含文件的完整路径(例如 /mnt/windows/images/pic.jpg )。如果您只想打印没有路径的文件名,可以使用以下任一方法:

Also note that $filename will contain the full path the the file (e.g. /mnt/windows/images/pic.jpg). If you want to only print the filename without the path, you can use either:

echo ${filename##*/}

或:

echo $(basename $filename)

第一个使用 Bash字符串操作更有效但可读性更低,后者通过拨打电话来实现 basename

The first uses Bash string maniputation which is more efficient but less readable, and the latter does so by making a call to basename.

这篇关于Bash确定文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆