Here are some useful sed commands.
Note. The option ‘-i’ is making the changes directly into the file without having to send the result to a temporary file, and then replace the original with the temporary file. Very useful …. and dangerous.
———————————–
Inserting a line of text at the beginning of the file
Sometimes you need to insert a line right at the beginning of the file. Here how to do it with sed.
Note: The ‘1’ in ‘1i … is not a small ‘l’ but a ‘1’ (number one).
sed -i '1i Line of text' filename
eg. Inserting the text ‘This is a line inserted at the beginning of a file’ at the beginning of the file /etc/motd
sed -i '1i This is a line inserted at the beginning of a file' /etc/motd
————————————
Deleting a line when you know the line number.
Very often I have been doing an ssh connection and was refused entry on the security grounds that the public key of the remote server does not match the one saved in the local host in the file ~/.ssh/known_hosts at line xx. To quickly remedy the case do the following command:
Note: ‘xx’ is the line number.
sed -i 'xx d' ~/.ssh/known_hosts
eg. Deleting the line 43 from the file ~/.ssh/known_hosts
sed -i '43 d' ~/.ssh/known_hosts
You can then retry the ssh connection and you will be asked to confirm the entry of the server’s public key in ~/.ssh/known_hosts. Type ‘yes’. That’s it.