How can I reverse a four length of letters with sed
?
For example:
the year was 1815.
Reverse to:
the raey was 5181.
This is my attempt:
cat filename | sed's/\([a-z]*\) *\([a-z]*\)/\2, \1/'
But it does not work as I intended.
How can I reverse a four length of letters with sed
?
For example:
the year was 1815.
Reverse to:
the raey was 5181.
This is my attempt:
cat filename | sed's/\([a-z]*\) *\([a-z]*\)/\2, \1/'
But it does not work as I intended.
Following awk may help you in same. Tested this in GNU awk and only with provided sample Input_file
This might work for you (GNU sed):
If there are no strings of the length required to reverse, bail out.
Prepend and append newlines to all required strings.
Insert a newline at the start of the pattern space (PS). The PS is divided into two parts, the first line will contain the current word being reversed. The remainder will contain the original line.
Each character of the word to be reversed is inserted at the front of the first line and removed from the original line. When all the characters in the word have been processed, the original word will have gone and only the bordering newlines will exist. These double newlines are then replaced by the word in the first line and the process is repeated until all words have been processed. Finally the newline introduced to separate the working line and the original is removed and the PS is printed.
N.B. This method may be used to reverse strings of varying string length i.e. by changing the first regexp strings of any number can be reversed. Also strings between two lengths may also be reversed e.g.
/\<w{2,4}\>/
will change all words between 2 and 4 character length.It's a recurrent problem so somebody created a bash command called "rev".
echo "$(echo the | rev) $(echo year | rev) $(echo was | rev) $(echo 1815 | rev)".
OR
echo "the year was 1815." | rev | tr ' ' '\n' | tac | tr '\n' ' '
Possible shortest
sed
solution even if a four length of letters contains_
s.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\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 wordstool with lookaround support would work for all cases
(?<![a-z0-9])
and(?!=[a-z0-9])
are negative lookbehind and negative lookahead respectivelyCan be shortened to
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