Operating on Lines by Number

Finding a line

We usually find a line with text or a regular expression, but we can also find it by its number. Let’s go back to the urls.txt file and explore this further.

Let’s comment on the first line of the file. We use the following command to target the first line and insert the comment character:

$ sed -e '1 {s/^/#/}' urls.txt

To comment on lines 2 through 4 of the file, we use the following command that specifies a range:

$ sed -e '2,4 {s/^/#/}' urls.txt

Prepending and appending lines

We can also manipulate the beginning and end of a file. Want to add a line to the top of the file? We use the number 1 to reference the first line of the file, followed by i and a backslash to indicate the text to insert. Add the text Bookmarks to the top of the file:

$ sed -e '1i\Bookmarks' urls.txt

To append a line to the end of the file, we use a dollar sign instead of a number, followed by a:

$ sed -e '$a\http://google.com' urls.txt

We can do multiple expressions in the same command, which means we can prepend and append text to a file in a single command. We just specify both expressions:

$ sed -e '1i\Bookmarks' -e '$a\http://google.com' urls.txt

We can prepend i and a with a line number to prepend or append text anywhere in the file. If we use i or a without a location, sed applies the operation for every line.

Changing a line in a file

In addition, we can change a specific line of the file using c. Let’s change example.com to github.com with the following command:

$ sed -e '1c\https://github.com' urls.txt

We can delete a line with d:

$ sed -e '1d' urls.txt

Run the complete code on the terminal below to practice the above commands.

cat << 'EOF' > urls.txt
http://example.com
http://facebook.com
http://twitter.com
https://pragprog.com
EOF
clear
sed -e '1d' urls.txt

Get hands-on with 1200+ tech skills courses.