guys! I am trying to exchange two words in a line but it doesn\'t work. For example: \"Today is my first day of university\" should be \"my is Today first day of university\"
You are not accounting for whitespace.
use [ \t]+ between words.
Try this:
sed -rn 's/(\w+\s)(\w+\s)(\w+\s)(.*)/\3\2\1\4/p' filename.txt
-n suppress automatic printing of pattern space
-r use extended regular expressions in the script
\s for whitespace
I start to make it with \s
which means any whitespaces chars.
I use it for match every words with [^\s]*
which match with everything but not spaces.
And I had \s*
for match withspaces between words. And don't forget to rewrite a space in replacement.
Look a this for an example:
sed 's#\([^ ]*\)\s+#\1 #'
( I use #
instead of /
)
This might work for you (GNU sed):
sed -r 's/(\S+)\s+(\S+)\s+(\S+)/\3 \2 \1/' file
sed -r 's/^(\w+)(\s+\w+\s+)(\w+)(.*)/\3\2\1\4/'
with your example:
kent$ echo "Today is my first day of university"|sed -r 's/^(\w+)(\s+\w+\s+)(\w+)(.*)/\3\2\1\4/'
my is Today first day of university
for your problem, awk is more straightforward:
awk '{t=$1;$1=$3;$3=t}1'
same input:
kent$ echo "Today is my first day of university"|awk '{t=$1;$1=$3;$3=t}1'
my is Today first day of university