バイナリファイルのレコード数を確認しようとしています。バイナリファイルのサイズはwc -c
。区切り文字が不明です。レコードサイズは固定されています。各レコードの正確なサイズがわかりません。レコード数を確認したい。
ベストアンサー1
この試み:
script.sh
:
#!/bin/bash
# read filename to var f from $1
f="$1"
# quit if file not found.
[ -f "$f" ] || { >&2 echo "File not found." ; exit 2; }
# total length of file (-1 to not count newline at the end of a file)
n=$(($(wc -c < "$f")-1))
# loop potential length of records, end at half total length of file.
for i in $(seq 1 $(awk -v n=$n 'BEGIN{print int((n/2)+0.5)-1}')); do
# now read all delimiters regarding record length from a file
# (see https://unix.stackexchange.com/a/276957/236063)
# and `sort -u` to get only individual ones
c=$(for ((j=i;j<n;j=j+i+1)); do printf '%s\n' $(dd ibs=1 skip=$j count=1 < "$f" 2>/dev/null); done | sort -u)
# if we have exactly one individual delimiter, we're done and can print length of record and the delimiter and exit.
if [ $(echo "$c" | wc -l) -eq 1 ]; then
printf 'l=%s d=%s\n' "$i" "$c"
exit 0
fi
done
>&2 echo "No delimiter found".
exit 1
コンテンツfile
:
abc,def,ghi
出力:
$ ./script.sh file
l=3 d=,
終了コード:
0 success, found delimiter and record length
1 no delimiter found
10 file not found
注:特に改行に関連するいくつかの問題を解決するには、いくつかの作業が必要だと思います。