Command to insert lines before first match

前端 未结 3 1178
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 05:46

I have file with the below info

testing
testing
testing

I want to insert a word(tested) before the first testing word using sed or any linu

相关标签:
3条回答
  • 2021-01-05 06:04

    Exactly:

    sed '0,/testing/s/testing/tested\n&/' file
    

    For lines containing "testing":

    sed '0,/.*testing.*/s/.*testing.*/tested\n&/' file
    

    For Lines Starting with "testing"

    sed '0,/^testing.*/s/^testing.*/tested\n&/' file
    

    For lines ending with "testing":

    sed '0,/.*testing$/s/.*testing$/tested\n&/' file
    

    To update the content of the file with the result add "-i", example:

    sed -i '0,/testing/s/testing/tested\n&/' file
    
    0 讨论(0)
  • 2021-01-05 06:08

    This might work for you (GNU sed):

    sed -e '/testing/{itested' -e ':a;n;ba}' file
    

    Insert tested before the first match of testing and then use a loop to read/print the remainder of the file.

    Or use the GNU specific:

    sed '0,/testing/itested' file
    
    0 讨论(0)
  • 2021-01-05 06:20

    To provide an awk-based alternative that is easier to understand:

    awk '!found && /testing/ { print "tested"; found=1 } 1' file
    
    • found is used to keep track of whether the first instance of testing has been found (variable found, as any Awk variable, defaults to 0, i.e., false in a Boolean context).
    • /testing/ therefore matches the first line containing testing, and processes the associated block:
      • { print "tested"; found=1 } prints the desired text and sets the flag that the first testing line has been found
    • 1 is a common shorthand for { print }, i.e., simply printing the current input line as is.
    0 讨论(0)
提交回复
热议问题