shell腳本如何確定文件是二進制還是文本?

[英]How can a shell script determine if a file is binary or text?


Have a situation where I need a shell or bash script to determine if a file is binary or not. The issue here is that the linux environment does not have file available and the grep version is from busybox which doesn't support -I. I found a perl method (the perl version is old supports -e but not -E) of it working but it's slow. Does anyone have a faster method of determining if a file is binary? TIA!!

有一種情況,我需要一個shell或bash腳本,以確定文件是否為二進制文件。這里的問題是linux環境沒有可用的文件,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

1 个解决方案

#1


3  

Avoid the time it takes to repeatedly load perl by doing all the work in Perl.

通過在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");
}

Usage:

用法:

do_test_text_file_on_dir ~/testdir/*

Note: !-B _ is equivalent to -T _ except for empty files.

注意:!- b_等於-T _除了空文件。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/10/24/72986c6f2b5736a547d9dae6e21bd8da.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com