gpt4 book ai didi

linux - shell 脚本如何确定文件是二进制文件还是文本文件?

转载 作者:太空狗 更新时间:2023-10-29 11:49:21 25 4
gpt4 key购买 nike

在这种情况下,我需要 shell 或 bash 脚本来确定文件是否为二进制文件。这里的问题是 linux 环境没有可用的 file 并且 grep 版本来自不支持 -I 的 busybox。我找到了一个 perl 方法(旧的 perl 版本支持 -e 但不支持 -E)它可以工作但速度很慢。有没有人有更快的方法来确定文件是否为二进制文件? TIA!!

#!/bin/sh

is_text_file() {
# grep -qI '.' "$1" ### busy box grep doesn't support
perl -e 'exit((-B $ARGV[0])?1:0);' "$1" ### works but is slow
}

do_test_text_file_on_dir() {
for f in "$1"/*; do
[ -f "$f" ] || continue
if is_text_file "$f"; then
echo "$f" is not a binary file
fi
done
}

do_test_text_file_on_dir ~/testdir

最佳答案

通过在 Perl 中完成所有工作,避免重复加载 perl 所花费的时间。

#!/usr/bin/perl

for (@ARGV) {
stat($_)
or warn("Can't stat \"$_\": $!\n"), next;

-f _ && !-B _
or next;

print("\"$_\" isn't a binary file\n");
}

用法:

do_test_text_file_on_dir ~/testdir/*

注意:!-B _ 等同于 -T _ 除了空文件。

关于linux - shell 脚本如何确定文件是二进制文件还是文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46920347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com