多次读取输入

考虑这个小例子:

2020-05-11--karli.txt:

Let me tell you what my sister's best friend told her last week about that Mr. Smith living in the little house next to the car park in that little village, what's it called, Br... no, Berekre... I don't know the name, but she said that Mr. Smith bought a budgie last week and it already flew away last Sunday! Isn't that funny?

shortenKarli.sh:

#!/bin/bash
inputFile=$1
shortenWords=4

numWords=`wc -w $inputFile | sed "s/^\([0-9]\+\).*/\1/g"`
introText=`cat $inputFile | cut -d' ' -f 1-$shortenWords`
outroText=`cat $inputFile | cut -d' ' -f $(expr $numWords - $shortenWords + 1)-$numWords`

echo "That were $numWords words, let me shorten it for you:"
echo "$introText... ...blah blah... ...$outroText"

呼唤

shortenKarli.sh 2020-05-11--karli.txt

带来

That were 63 words, let me shorten it for you: Let me tell you... ...blah blah... ...Sunday! Isn't that funny?

如预期的那样。

但是我如何修改脚本以从stdin读取,例如

phoneBot --callee=Karli --interruptions="Oh!;Mmh.;Well...;Really?" --speechrecognize=on | shortenKarli.sh

?它将需要读取相同的输入3次。

我可以将其写入临时文件,但是还有什么更优雅的方法吗?

评论
  • avelit
    avelit 回复

    您可以将其读入变量而不是临时文件。

    if [[ $# = 1 ]]
    then
        inputData=$(cat "$1")
    else
        inputData=$(cat)
    fi
    

    Then in place of $inputFile in the rest of the script, use <<<"$inputData"

    numWords=$(wc -w <<<"$inputData" | sed 's/^\([0-9]\+\).*/\1/g')
    introText=$(cut -d' ' -f 1-$shortenWords <<<"$inputData")
    outroText=$(cut -d' ' -f $(expr $numWords - $shortenWords + 1)-$numWords <<<"$inputData")