exchange two words using sed in Linux

后端 未结 5 1687
旧巷少年郎
旧巷少年郎 2021-01-26 04:08

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\"

5条回答
  •  伪装坚强ぢ
    2021-01-26 04:28

    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
    

提交回复
热议问题