正如其他人所指出的,sed 不太适合这项任务。这当然是可能的,这里有一个例子,它适用于带有空格分隔的单词的单行:
echo "She sells sea shells by the sea shore" |
sed 's/ /\n/g' | sed '/^[Ss]h/ s/[^[:punct:]]/./g' | sed ':a;N;$!ba;s/\n/ /g'
输出:
... sells sea ...... by the sea .....
第一个'sed'用换行符替换空格,第二个做点,第三个删除换行符,如this answer所示。
如果您有不可预测的单词分隔符和/或段落,这种方法很快就会变得难以管理。
编辑 - 多行替代
这是一种处理多行输入的方法,灵感来自Kent 的评论(GNU sed):
echo "
She sells sea shells by the sea shore She sells sea shells by the sea shore,
She sells sea shells by the sea shore She sells sea shells by the sea shore
She sells sea shells by the sea shore She sells sea shells by the sea shore
" |
# Add a \0 to the end of the line and surround punctuations and whitespace by \n
sed 's/$/\x00/; s/[[:punct:][:space:]]/\n&\n/g' |
# Replace the matched word by dots
sed '/^[Ss]h.*/ s/[^\x00]/./g' |
# Join lines that were separated by the first sed
sed ':a;/\x00/!{N;ba}; s/\n//g'
输出:
... sells sea ...... by the sea ..... ... sells sea ...... by the sea .....,
... sells sea ...... by the sea ..... ... sells sea ...... by the sea .....
... sells sea ...... by the sea ..... ... sells sea ...... by the sea .....