You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash实现句子单词反转并保留标点位置,求非awk/sed简化方案

寻求Bash下无需awk/sed的简化单词反转实现

需求是实现句子单词反转功能:输入句子后,反转其中单词的顺序,同时保留句末的终止标点(句号、问号、感叹号)位置,示例如下:

  • 输入:Enter a sentence: you can cage a swallow can't you?
  • 输出:Reversal of sentence: you can't swallow a cage can you?

要求通过逐字符读取存入一维char数组,识别终止标点后反向遍历输出单词。我尝试用tac结合tr交换空格与换行但未成功,最终用while循环完成了实现(代码如下),现寻求无需awk或sed的更简化实现方式。

#!/bin/bash
#set -x

read -rp "Enter a sentence: " -a sentence

if [ -z "$sentence" ]; then
echo "empty..exiting"
exit 1
fi

terminator=""

i=$((${#sentence[@]}-1))
while [ "$i" -ge 0 ]; do
   b=0
   while [ "$b" -lt "${#sentence[$i]}" ]; do
   if [ "${sentence[$i]:$b:1}" == "?" ] || \
   [ "${sentence[$i]:$b:1}" == "!" ] || \
   [ "${sentence[$i]:$b:1}" == "." ]; then
   terminator="${sentence[$i]:$b:1}"
   sentence["$i"]=$(tr -d [:punct:] <<<"${sentence[$i]}")
   break
   fi
   ((b++))
   done
echo -n "$(tr [A-Z] [a-z] <<<${sentence[$i]})"
if [ "$i" -gt 0 ]; then
echo -n " "
fi
((i--))
done

if [ -n "$terminator" ]; then
echo "$terminator"
else
echo
fi

exit 0

输入示例:

Enter a sentence: Every living thing is a masterpiece, written by nature and edited by evolution!

输出示例:

evolution by edited and nature by written masterpiece, a is thing living every!

内容的提问来源于stack exchange,提问作者Surepic 342

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 14:14:52