12

In a bash script I want to write some lines to a text file, but this file has already been used before and there are texts in it. So I want to echo some additional text in it, starting from a certain line number in the file.

I want something like this:

echo -fromLineNumber 33 -e "anything" >> textPath
Anthon
  • 78,313
  • 42
  • 165
  • 222
Ahmed Zain El Dein
  • 643
  • 2
  • 7
  • 8

2 Answers2

21

You can use sed to write at a particular line.

try this:

    sed -i '33ianything' textpath

or

    sed -i '33i\anything' textpath

It will insert "anything" in line number 33.

kumarprd
  • 436
  • 5
  • 10
2

To keep the first 32 lines and add new text afterwards:

head -n 32 oldfile > newfile
echo anything >> newfile
echo goes >> newfile
echo here >> newfile

To insert some text after line 32 of a file:

sed -e '32s/$/\nanything\ngoes\nhere/' oldfile > newfile
frostschutz
  • 47,228
  • 5
  • 112
  • 159
  • thank u , but i want to append on the old text file my new texts after a certain line number not to add in new file , i hope that i can make myself clear? – Ahmed Zain El Dein May 14 '13 at 17:28