How to append a line after a search result?

So I grep for something in some file:

grep "import" test.txt | tail -1 

In test.txt there is

import-one
import-two
import-three

some other stuff in the file

This will return the last search result:

import-three

Now how do I add some text -after-- import-three but before "some other stuff in the file". Basically I want to append a line but not at the end of a file but after a search result.


I understand that you want some text after each search result, which would mean after every matching line. So try

grep "import" test.txt | sed '/$/ aLine to be added'

You can try something like this with sed

sed '/import-three/ a
> Line to be added' t

Test:

$ sed '/import-three/ a
> Line to be added' t
import-one
import-two
import-three
Line to be added

some other stuff in the file

One way assuming that you cannot distingish between different "import" sentences. It reverses the file with tac , then find the first match (import-three) with sed , insert a line just before it ( i ) and reverse again the file.

The :a ; n ; ba :a ; n ; ba :a ; n ; ba is a loop to avoid processing again the /import/ match.

The command is written throught several lines because the sed insert command is very special with the syntax:

$ tac infile | sed '/import/ { i
"some text"
:a
n
ba }
' | tac -

It yields:

import-one
import-two
import-three
"some text"

some other stuff in the file
链接地址: http://www.djcxy.com/p/19642.html

上一篇: 如何让python回到代码中?

下一篇: 如何在搜索结果后添加一行?