我希望使用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/.//'
答案 0 :(得分: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//
答案 1 :(得分: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...