How to use sed to replace only the first occurrence in a file?

前端 未结 23 1406
别跟我提以往
别跟我提以往 2020-11-22 04:27

I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash s

23条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 04:45

    Nothing new but perhaps a little more concrete answer: sed -rn '0,/foo(bar).*/ s%%\1%p'

    Example: xwininfo -name unity-launcher produces output like:

    xwininfo: Window id: 0x2200003 "unity-launcher"
    
      Absolute upper-left X:  -2980
      Absolute upper-left Y:  -198
      Relative upper-left X:  0
      Relative upper-left Y:  0
      Width: 2880
      Height: 98
      Depth: 24
      Visual: 0x21
      Visual Class: TrueColor
      Border width: 0
      Class: InputOutput
      Colormap: 0x20 (installed)
      Bit Gravity State: ForgetGravity
      Window Gravity State: NorthWestGravity
      Backing Store State: NotUseful
      Save Under State: no
      Map State: IsViewable
      Override Redirect State: no
      Corners:  +-2980+-198  -2980+-198  -2980-1900  +-2980-1900
      -geometry 2880x98+-2980+-198
    

    Extracting window ID with xwininfo -name unity-launcher|sed -rn '0,/^xwininfo: Window id: (0x[0-9a-fA-F]+).*/ s%%\1%p' produces:

    0x2200003
    

提交回复
热议问题