在Unix中用sed反转四个字母的长度 [英] Reverse four length of letters with sed in unix
问题描述
如何用 sed
反转四个字母的长度?
How can I reverse a four length of letters with sed
?
例如:
the year was 1815.
反向:
the raey was 5181.
这是我的尝试:
cat filename | sed's/\([a-z]*\) *\([a-z]*\)/\2, \1/'
但是它没有按我的预期工作.
But it does not work as I intended.
推荐答案
不确定在所有情况下都可以使用GNU sed来实现.如果 _
不在四个字母单词前后立即出现,则可以使用
not sure it is possible to do it with GNU sed for all cases. If _
doesn't occur immediately before/after four letter words, you can use
sed -E 's/\b([a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])\b/\4\3\2\1/gi'
\ b
是单词边界,单词定义是任何字母,数字或下划线字符.因此 \ b
将确保仅匹配整个单词而不是单词的一部分
\b
is word boundary, word definition being any alphabet or digit or underscore character. So \b
will ensure to match only whole words not part of words
$ echo 'the year was 1815.' | sed -E 's/\b([a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])\b/\4\3\2\1/gi'
the raey was 5181.
$ echo 'two time five three six good' | sed -E 's/\b([a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])\b/\4\3\2\1/gi'
two emit evif three six doog
$ # but won't work if there are underscores around the words
$ echo '_good food' | sed -E 's/\b([a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])\b/\4\3\2\1/gi'
_good doof
具有环视支持的工具适用于所有情况
tool with lookaround support would work for all cases
$ echo '_good food' | perl -pe 's/(?<![a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])([a-z0-9])(?!=[a-z0-9])/$4$3$2$1/gi'
_doog doof
(?<![a-z0-9])
和(?!= [a-z0-9])
分别是负向后看和负向后看
(?<![a-z0-9])
and (?!=[a-z0-9])
are negative lookbehind and negative lookahead respectively
可以缩写为
perl -pe 's/(?<![a-z0-9])[a-z0-9]{4}(?!=[a-z0-9])/reverse $&/gie'
使用 e
修饰符将Perl代码放在替换部分中.这种形式适合于轻松更改要反转的单词的长度
which uses the e
modifier to place Perl code in substitution section. This form is suitable to easily change length of words to be reversed
这篇关于在Unix中用sed反转四个字母的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!