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 に答える