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

时间:2017-10-24 21:29:36

标签: linux bash shell perl

有一种情况我需要shell或bash脚本来确定文件是否是二进制文件。这里的问题是linux环境没有grep可用,而-I版本来自busybox,它不支持perl。我找到了一个#!/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版本旧支持-e但不支持-E),但它很慢。有没有人有更快的方法来确定文件是否是二进制文件? TIA !!

typedef struct
{
  int someVal;
} foo;

1 个答案:

答案 0 :(得分:3)

通过在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 _,但空文件除外。

相关问题