将 sed 中的特定字符移动到开头

将 sed 中的特定字符移动到开头

我想处理一个文件,该文件包含一些单词中间的特定字符,并将其移动到该单词的开头。它也可能出现在单词的开头,但在这种情况下,它应该保留在原来的位置。特殊字符是 ~。我的意思是:

原始文件:

This is a sentence with the cha~racter in the middle of a word.
This is a sentence with the ~character at the beginning of a word.
This is a sentence without the character.

预期结果:

This is a sentence with the ~character in the middle of a word.
This is a sentence with the ~character at the begining of a word.
This is a sentence without the character.

可以用 sed 脚本来完成吗?

答案1

$ sed 's/\b\(\w\+\)~\(\w\+\)\b/~\1\2/g' <<< 'This is a sentence with the cha~racter in the middle of a word.
> This is a sentence with the ~character at the beggining of a word.
> This is a sentence without the character.'
This is a sentence with the ~character in the middle of a word.
This is a sentence with the ~character at the beggining of a word.
This is a sentence without the character.

答案2

这可能对你有用:

sed 's/\<\([^~][^ ~]*\)~/~\1/g' file
This is a sentence with the ~character in the middle of a word.
This is a sentence with the ~character at the beggining of a word.
This is a sentence without the character.

相关内容