Linux
如何用 sed 和多個分隔符交換兩個單詞?
單詞中只接受字母,任何其他字元都是分隔符。我想用第三個詞交換第一個詞。
sed -E 's/([A-Za-z]+) [^A-Za-z] ([A-Za-z]+) [^A-Za-z] ([A-Za-z]+)/\3 \2 \1/' filename
我寫了這個但不能正常工作
例子:
I 4want5to%change
我想將此字元串更改為:
to 4want5I%change
任何的想法?
使用字元類
[[:alpha:]]
匹配大小寫和否定[^[:alpha:]]
匹配所有其他字元:sed -r 's/^([^[:alpha:]]*)([[:alpha:]]+)([^[:alpha:]]+[[:alpha:]]+[^[:alpha:]]+)([[:alpha:]]+)([^[:alpha:]]*)/\1\4\3\2\5/' file.txt
例子:
$ sed -r 's/^([^[:alpha:]]*)([[:alpha:]]+)([^[:alpha:]]+[[:alpha:]]+[^[:alpha:]]+)([[:alpha:]]+)([^[:alpha:]]*)/\1\4\3\2\5/' <<<'I 4want5to%change' to 4want5I%change $ sed -r 's/^([^[:alpha:]]*)([[:alpha:]]+)([^[:alpha:]]+[[:alpha:]]+[^[:alpha:]]+)([[:alpha:]]+)([^[:alpha:]]*)/\1\4\3\2\5/' <<<'4I 4want5to%change' 4to 4want5I%change $ sed -r 's/^([^[:alpha:]]*)([[:alpha:]]+)([^[:alpha:]]+[[:alpha:]]+[^[:alpha:]]+)([[:alpha:]]+)([^[:alpha:]]*)/\1\4\3\2\5/' <<<'Spring&summer^winter' winter&summer^Spring