How to Use sed to Append Line to End of a File


Often you may want to use sed to append a line to the end of a file.

You can use the following basic syntax to do so:

sed -i -e '$aMiami' cities.txt

This particular example appends a new line with the text “Miami” at the end of the file named cities.txt.

Here is what the various sed commands do:

  • The -i flag is used to modify the file in-place
  • The -e flag specifies that the next command should be executed as a sed program
  • The $ character is used to match the last line of the file
  • The a command is used to append a new line

Note: If you don’t want to modify the file in-place then you can simply leave out the -i flag.

The following example shows how to use this syntax in practice.

Example: Use sed to Append Line to End of File

Suppose we have a file named cities.txt that contains the names of various U.S. cities.

We can use the cat command to view the contents of this file:

Suppose that we would like to append a new line to the end of this file with the name “Miami.”

We can use the following syntax to do so:

sed -i -e '$aMiami' cities.txt

The following screenshot shows how to use this syntax in practice:

sed append line to end of file

Notice that when we use the cat command again to view the contents of the file that a new line with the string “Miami” has been added to the end of the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert a Line After Match
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply