1

我想使用sed. 但是,我希望表达式不要颠倒数字和特殊字符。

例如,考虑以下输入:

112358 is a fibonacci sequence...
a test line
124816 1392781
final line...

我的预期输出是:

112358 si a iccanobif ecneuqes...
a tset enil
124816 1392781
lanif enil... 

我已经以多种方式尝试过,但我找不到确切的表达方式。我尝试了以下表达式,但它反转了整个字符串:

sed '/\n/!G;s/\([.]\)\(.*\n\)/&\2\1/;//D;s/.//'
4

2 回答 2

3

这个 sed 脚本将完成这项工作:

#!/usr/bin/sed

# Put a \n in front of the line and goto begin.
s/^/\n/
bbegin

# Marker for the loop.
:begin

# If after \n is a lower case sequence, copy its last char before \n and loop.
s/\n\([a-z]*\)\([a-z]\)/\2\n\1/
tbegin

# If after \n is not a lower case sequence, copy it before \n and loop.
s/\n\([^a-z]*[^a-z]\)/\1\n/
tbegin

# Here, no more chars after \n, simply remove it before printing the new line.
s/\n//
于 2012-12-26T15:51:15.317 回答
3

我会用Perl这个。代码更具可读性:

perl -pe 's/\b([A-Za-z]+)\b/reverse($1)/ge' file

结果:

112358 si a iccanobif ecneuqes...
a tset enil
124816 1392781
lanif enil...
于 2012-12-26T16:02:01.257 回答