
使用 file 命令,我需要驗證許多文件是否為 ASCII 或其他格式
有時我從檔案指令中得到:
file1: ASCII English text
有時我從檔案指令中得到不同的答案
file2: Non-ISO extended-ASCII English text, with very long lines
我真的不確定是否有其他具有不同語法的答案
我的問題是:
我編寫了以下 ksh 語法來驗證檔案是否為 ASCII,但我不確定是否
以下語法是驗證 ASCII 格式的最佳語法嗎?
[[ ` file $some_file | grep –c ASCII ` = 1 ]] && print "you have ascii file for sure"
如果有人有其他建議來確定驗證 ASCII 格式!
答案1
if LC_ALL=C grep -q '[^[:print:][:space:]]' file; then
echo "file contains non-ascii characters"
else
echo "file contains ascii characters only"
fi
答案2
怎麼樣...
if file -ib "$file" | grep -Eqs '^text/plain(;|$)'; then
echo "It's text/plain."
fi
我不知道有多常見--mime-type
;如果是標準的,請使用
if file -b --mime-type "$file" | grep -qs '^text/plain$'; then
或grep -qs '^text/'
適用於任何文字類型。
答案3
由於您正在使用程式碼解析輸出,因此我建議使用該-i
選項,file
以便它輸出默劇類型而不是人類友好的字串。 MIME 類型輸出更規則,這使得在程式碼中處理起來更容易一些。
至於輸出類型看看人文件說:
/usr/share/file/magic
Default list of magic numbers
/usr/share/file/magic.mime
Default list of magic numbers, used to output mime types
when the -i option is specified.
查看這些文件中它可以報告的所有 MIME 類型,以確定在解析file
.我懷疑您所關心的只是 MIME 類型以text/
.