exchange two words using sed in Linux

后端 未结 5 1688
旧巷少年郎
旧巷少年郎 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:14

    You are not accounting for whitespace.

    use [ \t]+ between words.

    0 讨论(0)
  • 2021-01-26 04:17

    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

    0 讨论(0)
  • 2021-01-26 04:18

    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 /)

    0 讨论(0)
  • 2021-01-26 04:21

    This might work for you (GNU sed):

    sed -r 's/(\S+)\s+(\S+)\s+(\S+)/\3 \2 \1/' file 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题