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

You can use sed to write at a particular line.

try this:

    sed -i '33ianything' textpath


    sed -i '33i\anything' textpath

It will insert "anything" in line number 33.

  • It should work. Works fine for me in bash 4.2 and sed 4.2 in ubuntu. – kumarprd May 14 '13 at 17:55
  • 1
    wait a minute i will try again – Ahmed Zain El Dein May 14 '13 at 17:57
  • Thanks it works , it was my mistake in the first place thank u very much – Ahmed Zain El Dein May 14 '13 at 17:59
  • can i write it like this sed -i '$numberkanything' textPath out i must write down the number of line directly – Ahmed Zain El Dein May 14 '13 at 18:43
  • 3
    @AhmedZainElDein, the shell will not expand variables within single quotes. Also you have to tell the shell how to differentiate the variable name from the following text: sed -i "${number}i\anything" file – glenn jackman May 14 '13 at 21:36

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.