Sometimes you may be required to write or append multiple lines to a file. You can use multiple methods to write multiple lines to a file through the command line in the Linux system. Here are the three methods described below.

Advertisement

Method 1:-

You can write/append content line by line using the multiple echo commands. This the simple and straight forward solution to do this. We recommend going with Method 2 or Method 3.

echo "line 1 content" >> myfile.txt
echo "line 2 content" >> myfile.txt
echo "line 3 content" >> myfile.txt

Method 2:-

You can append content with the multi-line command in the quoted text. In this way can write multiple lines to fine with single echo command. But the third method is our suggested method to do this.

echo "line 1 content
line 2 content
line 3 content" >> myfile.txt

Method 3:-

This is the third and suggested option to use here documents (<<) to write a block of multiple lines text in a single command. The above methods are also useful but personally, I also use this while working.

cat >> greetings.txt <<EOL
line 1 content
line 2 content
line 3 content
EOL
Share.

11 Comments

  1. HI Sir ,
    I need to add multiple lines of text(22 lines ) at the beginning of a file .
    I have tried the method 3 above but apending happening at the End of File .Please help me with the command.In anticipation of your reply

    Thanks

  2. Hi sir,
    I need to add multiple lines of text(22 lines ) at the beginning of file.

    PLease help me with the command .In anticipation of your reply

  3. Hello , i want to append multiple lines to sshd_config.
    like below :
    Match Address
    PermitRootLogin without-password

    It should exactly in above format ..Could you please me using sed command

  4. i apand to this :- echo -n GENERICS_DOMAIN_FILE(`/etc/mail/sendmail.gdf’) jayesh.txt
    below error please any solution
    -bash: syntax error near unexpected token `(‘

    • Hi Jayesh, Use the command as following:

      echo -n 'GENERICS_DOMAIN_FILE(`/etc/mail/sendmail.gdf’)' >> jayesh.txt
      

      Using the -n will not add the trailing newline.

  5. sanjeevi kumran on

    I want to add a word in a specific line in the file. How can I do that? Do I need to mention the line number? Thanks in advance.

    • You can use the sed command to do this: Below example will append a string to line 4 in file.txt.

      sed -i ‘4s/$/ morestring/’ file.txt

Leave A Reply