On certain occasions we need to delete a specific line from a file or several, for example, it has happened to me that I have had a whole list of files and I need to delete line # 27 of all these (line # 27 is that of an ACL , norm, rule, configuration), I can either edit file by file or I can just achieve what I need using the thirst and a bash script (optional).
But, let's try a single file somewhat simple.
We have the file distros-deb.txt which contains this:
In other words, the file distros-deb.txt is in which we will put the Debian-based distros, but there we see that in line # 3 there is "archlinux", a distro that obviously has nothing to do with Debian, so we must eliminate that line. To eliminate line # 3 of that file we will put the following:
sed "3d" distros-deb.txt > distros-deb-ok.txt
Explaining this line is somewhat easy, with thirsty "3d" we are indicating that we will delete line # 3, with distros-deb.txt We indicate what file to work on, that is, delete line # 3 of this file, up to here if we press Enter it will show us what we want but in the terminal, so > distros-deb-ok.txt we are indicating that instead of showing the result in terminal, that it put it in a file with this name.
What is simple?
Also, we can avoid using the > distros-deb-ok.txt using a proper parameter of thirst, the parameter -i
That is, in case we want to delete the line from the file and save it with the same name (and not in another file), simply add the parameter -i :
sed -i "3d" distros-deb.txt
This will remove line # 3 from distros-deb.txt and save it.
What if I want a range of lines, that is to remove line # 3 but also # 4 and # 5? To achieve this we put the range from 3 to 5, that is:
sed -i "3,5d" distros-deb.txt
And it will show me only debian and kubuntu 😀
So what if I want to delete from line 2 to the last one, when I don't know the total lines?
Just use the dollar symbol - »$
sed -i "2,$d" distros-deb.txt
In case you want to eliminate from the first line to # 4 then we simply put the value 1 at the beginning:
sed -i "1,4d" distros-deb.txt
This has been everything, a very useful tip when you want to make bash scripts to automate tasks and you need to modify and eliminate lines of configuration files, to modify we can use thirst o perl, as well as to eliminate we already know how to do it with sed 😉