如何解决如何查看文件的大小是否是 4 字节的倍数
我正在为大学练习编写 bash 脚本,该脚本读取作为参数传递给它的文件的字节大小并将它们相加。如果大小是 4 字节的倍数,则添加大小。如果不是,我必须把它做成4的倍数。特别是练习的正文是这样写的:“如果文件的大小D不是4字节的倍数,则填写最后的D mod 4 字节,带零。 "
现在,为了检查文件的大小是否是 4 字节的倍数,我这样做了,但我不知道这是否正确:
D=`stat -c '%s' file.txt` #command sostitution
if (( ($D/4)*4 == $D ))
then
echo it's ok
else
echo it isn't ok
fi
我也想知道,给定文件的大小D(以字节为单位),如何填写最后的D 如果 D 不是 4 字节的倍数,则对 4 个字节取零。
问题是我不明白“填写最后一个D”是什么意思 mod 4 字节带零“.
解决方法
尝试以下操作:
d=$(stat -c '%s' file.txt)
if ((d % 4 != 0)); then
truncate -s "$(( (d + 3) / 4 * 4 ))" file.txt
fi
检查您的脚本
,
不是在模数处停止,而是直接计算要与 null
一起使用的 truncate
填充量:
#!/usr/bin/env sh
# Pad files with null to the alignment
# align ALIGNMENT FILE...
# $1: The alignemnt in bytes
# $@: The filenames to get aligned
####
# Example usage:
# align 4 file1.txt file2.txt file3.txt
# Take alignment as first argument
alignment=$1
# Shift first argument out
shift
# Iterate all remaining arguments as filename
for filename; do
# If filename is a real file and has write permission
if [ -f "$filename" ] && [ -w "$filename" ]; then
# Get file size in bytes
size=$(stat -c '%s' "$filename")
# Compute how much padding would be need for alignment
padding=$((alignment - size % alignment))
# If file need padding
if [ $padding -gt 0 ]; then
# Pad file with padding nulls
truncate -s +$padding "$filename"
fi
fi
done
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。