¿Abrir y escribir datos en un archivo de texto usando Bash?

Resuelto Adnan asked hace 12 años • 13 respuestas

¿Cómo puedo escribir datos en un archivo de texto automáticamente mediante scripts de shell en Linux?

Pude abrir el archivo. Sin embargo, no sé cómo escribirle datos.

Adnan avatar Jun 23 '12 01:06 Adnan
Aceptado

La respuesta corta:

echo "some data for the file" >> fileName

Sin embargo, echono trata los caracteres de fin de línea (EOF) de forma ideal . Entonces, si vas a agregar más de una línea, hazlo con printf:

printf "some data for the file\nAnd a new line" >> fileName

Los operadores >>y >son muy útiles para redirigir la salida de comandos , funcionan con muchos otros comandos bash.

Rocky Pulley avatar Jun 22 '2012 18:06 Rocky Pulley
#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2 # This comment will be inside of the file.
The keyword EOM can be any text, but it must start the line and be alone.
 EOM # This will be also inside of the file, see the space in front of EOM.
EOM # No comments and spaces around here, or it will not work.
text4 
EOM
coolfire avatar Aug 14 '2013 08:08 coolfire

Puede redirigir la salida de un comando a un archivo:

$ cat file > copy_file

o agregarle

$ cat file >> copy_file

Si desea escribir directamente el comando esecho 'text'

$ echo 'Hello World' > file
ssedano avatar Jun 22 '2012 22:06 ssedano
#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 
baetacos avatar Apr 24 '2014 20:04 baetacos