tags:

views:

67

answers:

2

Hello all

I need to reverse all string in text with 5 chars consecutive characters. For instance:

hello hi adams sde
abcde abs

Required output:

olleh hi smada sde
edcba  abs

I used:

sed -n 's\(a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)/\5\4\3\2\1/p' 

It reverses needed strings except "adams". Please help me fix this.

+1  A: 

Looks like it's not so much that "adams" isn't replaced, but that your command is only replacing the first matching instance. Try this:

sed -n 's/\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)/\5\4\3\2\1/pg' 

From the manual:

The s command can be followed by zero or more of the following flags:
g    Apply the replacement to all matches to the regexp, not just the first. 
(snip)
David M
you are almost right thank you:)sed -n 's/\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)/\5\4\3\2\1/pg'
Leo
Thanks - answer edited.
David M
so if you have a string like "powerful" , it will be "rewopful" ?
ghostdog74
Adding word boundaries would prevent longer words from getting mangled: `sed -n 's/\b\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)\([a-z]\)\b/\5\4\3\2\1/pg'` (GNU extension)
Dennis Williamson
+1  A: 

use awk

awk '{
    for(i=1;i<=NF;i++) {
        if(length($i)==5) {
            v=""
            for(o=length($i);o>0;o--) {
                v=v substr($i,o,1)
            }
            $i=v
        }
    }
}1' file

output

$ more file
hello hi adams sde
abcde abs
$ ./shell.sh
olleh hi smada sde
edcba abs
ghostdog74