
我正在嘗試找到一種有效的方法來做到這一點OverTheWire 強盜挑戰第 5 級。
無論如何,我有一堆文件,但只有一個符合以下條件:
- 人類可讀
- 大小為 1033 位元組
- 不可執行
現在,我正在使用find
命令。我能夠找到符合最後兩個條件的文件:
find . -size 1033c ! -executable
但是,我不知道如何排除非人類可讀的文件。我為該挑戰找到的解決方案使用-readable
測試參數,但我認為這行不通。-readable
只查看檔案的權限,而不查看其內容,而挑戰描述則要求提供 ASCII 檔案或類似檔案。
答案1
是的,您可以用來find
尋找大小合適的非可執行文件,然後用來file
檢查 ASCII。就像是:
find . -type f -size 1033c ! -executable -exec file {} + | grep ASCII
然而,問題並不像聽起來那麼簡單。 「人類可讀」是一個非常模糊的術語。想必您指的是文本。好的,但是什麼樣的文字呢?僅限拉丁字元 ASCII?完整的統一碼?例如,考慮這三個文件:
$ cat file1
abcde
$ cat file2
αβγδε
$ cat file3
abcde
αβγδε
$ cat file4
#!/bin/sh
echo foo
這些都是文本和人類可讀的。現在,讓我們看看file
它們是什麼:
$ file *
file1: ASCII text
file2: UTF-8 Unicode text
file3: UTF-8 Unicode text
file4: POSIX shell script, ASCII text executable
因此,find
上面的命令只會尋找file1
(為了這個範例,我們假設這些檔案有 1033 個字元)。您可以展開 來find
查找字串text
:
find . -type f -size 1033c ! -executable -exec file {} + | grep -w text
使用-w
,將僅列印作為獨立單字找到的grep
行。text
那應該非常接近您想要的內容,但我不能保證沒有其他文件類型的描述也可能包含 string text
。
答案2
雖然-exec
主要用於對找到的文件執行某些操作,但它也可以充當測試。因此,我們可以將其添加到您的其他標準中:
find . \
-size 1033c \
-not -executable \
-exec sh -c 'file {} | grep "text$"' \;
請記住,grep
當未找到模式時傳回非零,sh -c "COMMAND"
並將傳回評估結果(只要它有效)。因此,這只會列印file <filename>
以 結尾的文件text
,例如“UTF-8 Unicode 文字”或“ASCII 文字”,但不會列印“帶有轉義序列的非 ISO 擴展 ASCII 文字”。
在一行中,它甚至比 over 還要短xargs
:
find . -size 1033c -not -executable -exec sh -c 'file {} | grep "text$"' \;
請記住,您可以替換sh -c 'file {} | grep "text$"'
為任何自訂命令。如果您想檢查非常複雜的內容,最好提供一個 shell 腳本並使用它:
find . -size 1033c -not -executable -exec is_human_readable.sh {} \;
從長遠來看,它比 shell 的歷史記錄更容易維護:
#!/bin/sh
file "$@" | grep "text$" > /dev/null
答案3
只有 1 個位元組1033
大小的檔案。
bandit5@bandit:~$ find -size 1033c
./inhere/maybehere07/.file2
bandit5@bandit:~$
為什麼1033c
又不呢1033
?檢查man
頁面
-size n[cwbkMG] File uses n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for Kilobytes (units of 1024 bytes) `M' for Megabytes (units of 1048576 bytes) `G' for Gigabytes (units of 1073741824 bytes)
ls -l
用and命令驗證一下file
,你就得到了所有的答案。
bandit5@bandit:~$ ls -l ./inhere/maybehere07/.file2
-rw-r----- 1 root bandit5 1033 May 7 20:15 ./inhere/maybehere07/.file2
bandit5@bandit:~$
bandit5@bandit:~$ file ./inhere/maybehere07/.file2
./inhere/maybehere07/.file2: ASCII text, with very long lines
bandit5@bandit:~$
- 人類可讀 (
ASCII text
) - 大小為 1033 位元組(也在
ls -l
輸出) - 不可執行 (
-rw-r-----
)
答案4
find . -size 1033c ! -executable -exec file {} +