1
{  
  This is test1  
  this is test2  
  this is test3  
}

Now i want append multiple lines before the last line using echo command Anyone please help me!!!!

My output is look like below

{  
  This is test1  
  this is test2  
  this is test3  
  this is test4  
  this is test5  
}  

Using Echo Commands not sed or awk

0

You can use head with echo to achieve this

  cat <outputfilename> | head -n -1  && echo -e "  this is test4\n  this is test5\n  this is test6\n}"

If you want to append the output in a file , just use ">" output redirection

  (cat <outputfilename> | head -n -1  && echo -e "  this is test4\n  this is test5\n  this is test6\n}") > <RESULTFILENAME>
1

sed is the correct way of doing this, even if you said that you for some reason don't want to use sed.

The sed script would look like

$i\
  this is test4\
  this is test5

and you would run that as sed -f script.sed file. The i command inserts lines before the addressed line, and the $ addresses the last line of the file.

As a "one-liner" using GNU sed:

$ sed -e '$i\' -e '  this is test4\' -e '  this is test5' file
{
  This is test1
  this is test2
  this is test3
  this is test4
  this is test5
}

Depending on whether the file is actually a JSON file or in some other structured text format, there may be tools like jq that are better suited for manipulating it.


To use echo as you requested (this also assumes that you are using head from GNU coreutils as the -n option does not usually take a negative number):

{   head -n -1 file
    echo '  this is test4'
    echo '  this is test5'
    tail -n 1 file; } >newfile
  • Its working but i am using echo command in whole file and now i don't change that if you have answer that please share with me i need that – Sunil Makwana Jun 19 '18 at 6:02
  • @SunilMakwana See added bit at the end. – Kusalananda Jun 19 '18 at 6:25

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.