¿Cómo puedo añadir texto a un archivo?


¿Cuál es la forma más fácil de añadir texto a un archivo en Linux?

Eché un vistazo a esta pregunta, pero la respuesta aceptada usa un programa adicional (sed) Estoy seguro de que debería haber una manera más fácil con echo o similar.

Author: Community, 2013-07-17

4 answers

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Esencialmente, puede volcar cualquier texto que desee en el archivo. CTRL-D envía una señal de fin de archivo, que termina la entrada y te devuelve al shell.

 88
Author: Jon Kiparsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-18 21:52:53

Qué tal:

echo "hello" >> <filename>

Usando el operador >> agregará datos al final del archivo, mientras que usando el > sobrescribirá el contenido del archivo si ya existe.

También puedes usar printf de la misma manera:

printf "hello" >> <filename>

Tenga en cuenta que puede ser peligroso usar lo anterior. Por ejemplo, si ya tiene un archivo y necesita agregar datos al final del archivo y se olvida de agregar el último > todos los datos en el archivo serán destruidos. Puedes cambiar esto comportamiento al establecer la variable noclobber en su .bashrc:

set -o noclobber

Ahora cuando trates de hacer echo "hello" > file.txt recibirás una advertencia diciendo cannot overwrite existing file.

Para forzar la escritura en el archivo, ahora debe usar la sintaxis especial:

echo "hello" >| <filename>

También debe saber que por defecto echo agrega un carácter de nueva línea final que se puede suprimir mediante el uso de -n bandera:

echo -n "hello" >> <filename>

Referencias

 125
Author: Cyclonecode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-06 15:45:32

Otra forma posible es:

echo "text" | tee -a filename >/dev/null

El -a se añadirá al final del archivo.

Si necesita sudo, use:

echo "text" | sudo tee -a filename >/dev/null
 19
Author: xyz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-18 02:44:13

Seguimiento a la respuesta aceptada.

Necesita algo que no sea CTRL-D para designar el final si usa esto en un script. Prueba esto en su lugar:

cat << EOF >> filename
This is text entered via the keyboard or via a script.
EOF

Esto agregará texto al archivo indicado (sin incluir "EOF").

Utiliza un here document (o heredoc).

Sin embargo, si necesita añadir sudo al archivo indicado, tendrá problemas para utilizar un heredoc debido a la redirección de E/S si está escribiendo directamente en la línea de comandos.

Esta variación funcionará cuando esté escribiendo directamente en la línea de comandos:

sudo sh -c 'cat << EOF >> filename
This is text entered via the keyboard.
EOF'

O puede usar tee en su lugar para evitar el problema de la línea de comandos sudo visto cuando se usa heredoc con cat:

tee -a filename << EOF
This is text entered via the keyboard or via a script.
EOF
 8
Author: user12345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-15 07:59:02