Wolfr
Wolfr

Reputation: 5164

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.

Upvotes: 2

Views: 250

Answers (4)

glenn jackman
glenn jackman

Reputation: 246867

Using ed:

ed test.txt <<END
$
?^import
a
inserted text
.
w
q
END

Meaning: go to the end of the file, search backwards for the first line beginning with import, add the new lines below (insertion ends with a "." line), save and quit

Upvotes: 1

Birei
Birei

Reputation: 36272

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 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

Upvotes: 1

Bj&#246;rn Labitzke
Bj&#246;rn Labitzke

Reputation: 126

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 '/$/ a\Line to be added'

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77105

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

Upvotes: 1

Related Questions