Reputation: 1528
Consider this small example:
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"
Calling
shortenKarli.sh 2020-05-11--karli.txt
brings
That were 63 words, let me shorten it for you: Let me tell you... ...blah blah... ...Sunday! Isn't that funny?
as expected.
But how could I modify the script to read from stdin, like
phoneBot --callee=Karli --interruptions="Oh!;Mmh.;Well...;Really?" --speechrecognize=on | shortenKarli.sh
? It would need to read the same input 3 times.
I could write it to a temporary file, but is there something more elegant?
Upvotes: 2
Views: 358
Reputation: 780929
You could read it into a variable instead of a temporary file.
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")
Upvotes: 4