簡體   English   中英

bash獲取wc -l號並在一個命令中顯示?

[英]bash obtain wc -l number and display in one command?

我很確定這會很明顯,但目前我這樣做:

count=`find $dir -type f \( -perm -007 \) -print 2>/dev/null | wc -l`

這讓我得到了我想要的數字,但是不要在屏幕上顯示任何內容(盡管我無論如何都會丟失錯誤行)。

有沒有辦法做到這一點(獲取wc -l計數到count變量),同時還在一個命令中顯示輸出到控制台? 我很確定在這里可以使用像tee這樣的東西,但是我的大腦並沒有像它應該的那樣工作。

否則,我想寫一個臨時文件和控制台使用teecat它回到wc會起作用,但我相信必須有一個更優雅的方法來做到這一點。

編輯: 對不起,似乎問題不清楚。 我不想顯示屏幕的計數,我想顯示我一直在計算的輸出,即:來自find的輸出

啊,所以你想要打印正常輸出,並且在$count有匹配$count

嘗試這個:

count=`find $dir -type f \( -perm -007 \) -print 2>/dev/null | tee /dev/tty | wc -l`

好的,然后回答更新的問題

tty方法很好,但會在非終端上失敗(例如ssh localhost'echo hello> / dev / tty'失敗)

它可能只是

count=`find $dir -type f \( -perm -007 \) -print 2>/dev/null | tee >(cat >&2) | wc -l`

這相當於

count=`find $dir -type f \( -perm -007 \) -print 2>/dev/null | tee /proc/self/fd/2 | wc -l`

如果你不想/不能在這里使用stderror(fd 2)作為sidechannel,那么你可以打開原始stdout的副本並改為引用它:

exec 3>&1
count=`find $dir -type f \( -perm -007 \) -print 2>/dev/null | tee /proc/self/fd/3 | wc -l`

$ 0.02

更新我在問題更新后添加了另一個答案

unset x
echo ${x:="$(find $dir -type f \( -perm -007 \) -print 2>/dev/null | wc -l)"}
echo $x

產量

16
16

以下是您澄清問題的答案。 這將計數置於變量$ count中並顯示find的輸出:

found=$(find $dir type f \( -perm -007 \) -print 2>/dev/null)
count=$(echo -e "$found" | wc -l)
echo -e "$found"

我不確定我完全理解,因為find命令,如所寫,不需要括號,不應該產生任何錯誤,我不知道你是否需要將輸出轉到stdout或者如果你只是想看到它工作,在這種情況下,stderr也可以正常工作。 我會這樣做:

count=`find $dir -type f -perm -007 -print -fprint /dev/stderr | wc -l`

你可以找到打印的輸出到屏幕,如果你tee (通過匿名FIFO這里)find命令的標准輸出到標准錯誤。

如果您的文件名或路徑嵌入了換行符,那么您的計數就會出錯。 因此,使用find的-print0功能,然后使用tr命令刪除所有不是 '\\ 0'的字節,最后只用最后的wc命令計算'\\ 0'字節。

# show output of find to screen
count=`find . -type f \( -perm -007 \) -print0 2>/dev/null | tee >(tr '\0' '\n' > /dev/stderr) | tr -dc '\0' |  wc -c`
echo "$count"

# show output of count to screen
count=`find . -type f \( -perm -007 \) -print0 2>/dev/null | tee >(tr -dc '\0' | wc -c > /dev/stderr) | tr -dc '\0' |  wc -c`
echo "$count"

暫無
暫無

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

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