¿Abrir y escribir datos en un archivo de texto usando Bash?
¿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.
Aceptado
La respuesta corta:
echo "some data for the file" >> fileName
Sin embargo, echo
no 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.
#!/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
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
#!/bin/bash
cat > FILE.txt <<EOF
info code info
info code info
info code info
EOF