Replacing first occurance of a match with sed

前端 未结 3 1843
闹比i
闹比i 2021-01-07 03:25

I am doing a find and replace with sed, replacing the BASH variable $a (when at the start of a new line) with the BASH variable $b:



        
相关标签:
3条回答
  • This might work for you:

     sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
    

    Or:

     sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file
    
    0 讨论(0)
  • 2021-01-07 04:00

    This should work:

    sed -i "0,/^\$a/s//\$b/" ./file.txt
    

    You can read more about this at http://www.grymoire.com/Unix/Sed.html#toc-uh-29

    0 讨论(0)
  • 2021-01-07 04:01

    One way using sed:

    sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
    

    Explanation:

    s/^$var1/$var2/             # Do substitution.
    ta                          # If substitution succeed, go to label `:a`
    b                           # Substitution failed. I still haven't found first line to 
                                # change, so read next line and try again.
    :a                          # Label 'a'
    N                           # At this position, the substitution has been made, so begin loop
                                # where I will read every line and print until end of file.
    ba                          # Go to label 'a' and repeat the loop until end of file.
    

    A test with same example provided by Jaypal:

    Content of infile:

    ab aa
    ab ff
    baba aa
    ab fff
    

    Run the command:

    sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
    

    And result:

    bb aa
    ab ff
    baba aa
    ab fff
    
    0 讨论(0)
提交回复
热议问题