I'm doing a network configurator in bash, and I need to add several lines to the /etc/resolv.conf
file. Doing echo "hola" » fichero.txt
is added to the end, but how do I get it added to the start?
I'm doing a network configurator in bash, and I need to add several lines to the /etc/resolv.conf
file. Doing echo "hola" » fichero.txt
is added to the end, but how do I get it added to the start?
There are different ways of doing it. First of all, but, it is important to remember that the file /etc/resolv.conf
is sensitive and modifying it erroneously can have bad consequences. Therefore, always backs up before modifying .
As we see in How to insert a text at the beginning of a file? we can use these methods:
echo "hola" | cat - fichero > nuevo_fichero
sed '1s/^/hola\n/' fichero > nuevo_fichero
{ printf "hola\n"; cat fichero; } > nuevo_fichero
They all create a new file. If you want to edit the file itself, use sed -i.bak '...' fichero
. This will modify fichero
and create a backup called fichero.bak
.
Tests:
$ cat fichero
1
2
3
$ echo "hola" | cat - fichero
hola
1
2
3
$ sed '1s/^/hola\n/' fichero
hola
1
2
3
Editing the same file with i
:
$ sed -i.bak '1s/^/hola\n/' fichero
$ cat fichero
hola # ¡el original se modificó!
1
2
3
$ cat fichero.bak
1 # ¡es una copia de seguridad!
2
3