2

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.

Wolfr
  • 5,055
  • 4
  • 25
  • 31
  • See http://stackoverflow.com/questions/9081/grep-a-file-but-show-several-surrounding-lines – lurker May 28 '13 at 15:33
  • After each block of matches, or the first block of matching lines, or the last? The first two are easier. – tripleee May 28 '13 at 15:36

4 Answers4

2

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'
Björn Labitzke
  • 126
  • 1
  • 1
  • 5
1

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
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
  • 1
    As *import-three* may change, what about making it more general? Something like `text=$(grep "import" test.txt | tail -1)` and then `sed "/$text/ a\..."` – fedorqui May 28 '13 at 15:37
  • True .. `Give a man a fish and you feed him for a day. Teach a man how to fish and you feed him for a lifetime.` :) – jaypal singh May 28 '13 at 15:44
1

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
Birei
  • 35,723
  • 2
  • 77
  • 82
1

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352