Insert text before a certain line using Bash

前端 未结 5 1443
时光说笑
时光说笑 2020-12-17 04:24

How can I insert a set of lines (about 5) into a file at the first place a string is found?

For example:

BestAnimals.txt

dog         


        
5条回答
  •  悲哀的现实
    2020-12-17 04:43

    I would:

    1. Use grep to find the line number of the first match
    2. Use head to get the text leading up to the match
    3. Insert the new content using cat
    4. Use tail to get the lines after the match

    It's neither quick, efficient nor elegant. But it's pretty straight-forward, and if the file isn't gigantic and/or you need to do this many times a second, it should be fine.

提交回复
热议问题