Command to insert lines before first match

前端 未结 3 1199
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题