簡體   English   中英

為什么`echo $(find) | wc -l`沒有正確計算文件數?

[英]Why does `echo $(find) | wc -l` not count the number of files correctly?

那是我的 function

function getFile(){
    echo $(find . -type f -regextype egrep -regex ${REGEX:-'.*\.(jpe?g|JPE?g)$'})
}

當我嘗試在我的其他功能中獲得該 getFile 返回時

function resize(){
    (( i=1 ))
    local k=`getFile | wc -l`
    echo $k
}

如果我這樣做,我不會得到相同的結果

function resize(){
    (( i=1 ))
    local k=`find . -type f -regextype egrep -regex ${REGEX:-'.*\.(jpe?g|JPE?g)$'} | wc -l`
    echo $k
}

問題出在getFile function 中。 您在那里所做的是找到 jpeg(或其他)文件的名稱,然后echo顯這些文件。 它所做的是將所有這些打印在一行中。 例如,這就是我所擁有的

./photo_2019-07-18_22-20-451.jpg ./photo_2019-07-18_22-20-45.jpg

然后你試着用wc -l計算那些,它基本上計算 output 中的行數,因此它總是得到 1。

另一方面,在第二個 function 中,您不再回顯它不再是單行的結果,而是給出了正確的答案。

只需從getFile()中刪除echo ,它就會起作用

function getFile() {
    find . -type f -regextype egrep -regex ${REGEX:-'.*\.(jpe?g|JPE?g)$'};
}

它輸出

$ getFile

./photo_2019-07-18_22-20-451.jpg
./photo_2019-07-18_22-20-45.jpg

最后

function resize(){
    (( i=1 ))
    local k=`getFile | wc -l`
    echo $k
}
$ resize
2

find中計算 output 的行數很脆弱,因為可以想象文件名可能包含換行符。 由於您似乎不受 POSIX 兼容性的限制,我會使用類似的東西

find . -type f -regextype egrep -regex "${REGEX:-.*\.(jpe?g|JPE?g)$}" -printf '.' | wc -c

得到計數。 (不管文件名是什么, find只輸出一個字符wc計數。)

如果您有時仍需要getFile來生成實際文件名(需要注意的是,單個 output 行可能不是完整的文件名),您可以參數化 function,例如:

getFile () {
  find_opts=(. -type f -regextype egrep -regex ${REGEX:-'.*\.(jpe?g|JPE?g)$'})
  count=
  for arg; do
    case $arg in
      -c) find_opts+=(-printf '.'); count=1 ;;
    esac
  done

  find "${find_opts[@]}" | if [ -z "$count" ]; then cat; else wc -c; fi
}

然后你可以運行

$ getfile
foo.jpg
bar.jpg

或者

$ getfile -c
2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM