โซลูชันทั่วไปเพื่อประมวลผลไฟล์ที่ไม่ใช่ไบนารีเท่านั้นเมื่อbashใช้file -b --mime-encoding:
while IFS= read -d '' -r file; do
[[ "$(file -b --mime-encoding "$file")" = binary ]] &&
{ echo "Skipping $file."; continue; }
echo "Processing $file."
# ...
done < <(find . -type f -print0)
ฉันติดต่อผู้เขียนยูทิลิตี้ไฟล์และเขาเพิ่ม-00พารามิเตอร์ที่ดีในเวอร์ชั่น 5.26 (เปิดตัว 2016-04-16, เช่นใน Arch ปัจจุบันและ Ubuntu 16.10) ซึ่งพิมพ์file\0result\0ไฟล์หลายไฟล์พร้อมกันในวิธีนี้คุณสามารถทำได้ เช่น:
find . -type f -exec file -00 --mime-encoding {} + |
awk 'BEGIN{ORS=RS="\0"}{if(NR%2)f=$0;else if(!/binary/)print f}' | …
( awkส่วนหนึ่งคือการกรองไฟล์ทุกไฟล์ที่ไม่ใช่แบบไบนารีไม่ใช่ORSตัวแยกผลลัพธ์)
สามารถใช้ในวงแน่นอน:
while IFS= read -d '' -r file; do
echo "Processing $file."
# ...
done < <(find . -type f -exec file -00 --mime-encoding {} + |
awk 'BEGIN{ORS=RS="\0"}{if(NR%2)f=$0;else if(!/binary/)print f}')
จากสิ่งนี้และก่อนหน้านี้ฉันสร้างbashสคริปต์เล็กน้อยสำหรับการกรองไฟล์ไบนารีซึ่งใช้วิธีการใหม่โดยใช้-00พารามิเตอร์ของfileในเวอร์ชันที่ใหม่กว่าและกลับไปยังวิธีก่อนหน้าในเวอร์ชันเก่า:
#!/bin/bash
# Expects files as arguments and returns the ones that do
# not appear to be binary files as a zero-separated list.
#
# USAGE:
# filter_binary_files.sh [FILES...]
#
# EXAMPLE:
# find . -type f -mtime +5 -exec ./filter_binary_files.sh {} + | xargs -0 ...
#
[[ $# -eq 0 ]] && exit
if [[ "$(file -v)" =~ file-([1-9][0-9]|[6-9]|5\.([3-9][0-9]|2[6-9])) ]]; then
file -00 --mime-encoding -- "$@" |
awk 'BEGIN{ORS=RS="\0"}{if(NR%2)f=$0;else if(!/binary/)print f}'
else
for f do
[[ "$(file -b --mime-encoding -- "$f")" != binary ]] &&
printf '%s\0' "$f"
done
fi
หรือที่นี่อีก POSIX-y หนึ่ง แต่ต้องการการสนับสนุนสำหรับsort -V:
#!/bin/sh
# Expects files as arguments and returns the ones that do
# not appear to be binary files as a zero-separated list.
#
# USAGE:
# filter_binary_files.sh [FILES...]
#
# EXAMPLE:
# find . -type f -mtime +5 -exec ./filter_binary_files.sh {} + | xargs -0 ...
#
[ $# -eq 0 ] && exit
if [ "$(printf '%s\n' 'file-5.26' "$(file -v | head -1)" | sort -V)" = \
'file-5.26' ]; then
file -00 --mime-encoding -- "$@" |
awk 'BEGIN{ORS=RS="\0"}{if(NR%2)f=$0;else if(!/binary/)print f}'
else
for f do
[ "$(file -b --mime-encoding -- "$f")" != binary ] &&
printf '%s\0' "$f"
done
fi
fileยูทิลิตีที่ใดที่หนึ่งในสคริปต์ / ไปป์ไลน์ของคุณเพื่อระบุว่าไฟล์นั้นเป็นข้อมูลหรือข้อความ