我正在创建一个脚本,该脚本将在 FM 广播电台名称中显示歌曲名称的两倍。广播电台名称限制为 8 个字符。可以说我有这一行:Best Direction - I feel good
代码将如下所示:(“PS”是行软件的开头,知道它是更改名称的命令)
echo "PS Best" > $fifo;
sleep 1;
echo "PS Directio" > $fifo;
sleep 1;
echo "PS n - I" > $fifo;
sleep 1;
echo "PS feel" > $fifo;
sleep 1;
echo "PS good" > $fifo;
sleep 1;
//repeat this one more time
如何在 bash 脚本中做到这一点?我不知道。
答案1
与fold
从GNU 核心实用程序:
a="Best Direction - I feel good"
fold -s -w 8 <<< "$a" | while read -r line; do
echo "PS $line" > "$fifo"
sleep 1
done
输出到$fifo:
最佳PS PS方向 PS n-I PS感觉 PS好
没有fold
与 $fifo 相同的输出:
a="Best Direction - I feel good"
while [[ -n $a ]]; do # loop until $a is empty
if [[ ${#a} -gt 8 ]]; then
b="${a:0:8}" # get first 8 characters of $a
c="${b% *}" # crop all from right incl. first whitespace
else
c="$a"
fi
echo "PS $c" > "$fifo"
d="${a#$c}" # crop $c left from string $a
a="${d# *}" # remove a leading whitespace
sleep 1
done