Reputation: 907
I need something which reverts words in a sentence in opposite order. I am sure it is possible to do without writing a script.
Something which receives an input stream like echo AAaa BBbb CCcc | foo
and prints CCcc BBbb AAaa
Sorry, I changed the example, the words themselves should not be reverted. So, rev does not work
Upvotes: 0
Views: 333
Reputation: 16750
A cryptic version usind sed, working on multi-line input, and spaces between words and at the beginning/end of the line:
echo -e " AAaa BBbb CCcc\nZ Y X" | sed -e 'G;:a;s/^\([^ ]*\) \(.*\)\n\(.*\)$/\2\n \1\3/;ta;s/\n//'
What it does is:
G
command),s
command),Upvotes: 1
Reputation: 16750
In pure bash, so without needing a subprocess, and working on multi-line input like the awk solution, but not working if many spaces between words of at the beginning/end of the line :-(:
function revert_line_in() {
test $# -eq 0 && return
test $# -eq 1 && echo -n "$1"
test $# -eq 1 || { local word=$1; shift; revert_line_in $@; echo -n " $word"; }
}
function revert_line() {
while read line; do revert_line_in $line; echo; done
}
echo -e " AAaa BBbb CCcc\nthis is another test example" | revert_line
revert_line <<< "AAaa BBbb CCcc
this is another test example"
revert_line < file
Note the local
keyword in the function that declare local variable. If omitted, the solution breaks.
Upvotes: 0
Reputation: 2204
sure there is, its rev
:
~ $ echo AAA BBB CCC DDD | rev
DDD CCC BBB AAA
~ $
EDIT:
Ok, so you may also try using tac
this way:
~ $ echo -n "AAaa BBbb CCcc DDdd " | tac -s ' '
DDdd CCcc BBbb AAaa ~ $
The only problem is it doesn't display new line at the end of the string.
Upvotes: 5
Reputation: 195079
well when I saw this question, I thought tac or rev too. however I guess OP made a bad example with AAA BBB. he may want to revert "word"s but not all characters.
see this, if it is what you want:
kent$ echo "this is another test example"|awk '{for(i=NF;i>0;i--)printf $i" "}'
example test another is this
Upvotes: 6