
me estoy adaptandoeste guiónpara insertar el contenido de un archivo en otro archivo. Esto es lo que tengo ahora:
#!/bin/sh
# Check if first and second parameters exist
if [ ! -z "$2" ]; then
STRING=$(cat $1)
# Check if the supplied file exist
if [ -e $2 ]; then
sed -i -e "2i$STRING" $2
echo "The string \"$STRING\" has been successfully inserted."
else
echo "The file does not exist."
fi
else
echo "Error: both parameters must be given."
fi
Lo ejecuto con:./prepend.sh content.txt example.txt
El content.txt
archivo:
first_line
second_line
El example.txt
archivo:
REAL_FIRST_LINE
REAL_SECOND_LINE
La salida del guión:
sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.
Y el contenido del example.txt
archivo sigue siendo el mismo, cuando quiero que sea así:
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
Respuesta1
Suena como si quisierasEl r
comando:
sed "1r $1" "$2"
Es posible que puedas hacer esto con GNU sed:
cat "$1" | sed '2r /dev/stdin' "$2"
Respuesta2
En la versión GNU de sed
, puede usar el r
comando (leer) para leer e insertar el contenido del archivo directamente en una dirección de línea determinada.
r filename
As a GNU extension, this command accepts two addresses.
Queue the contents of filename to be read and inserted into the output stream
at the end of the current cycle, or when the next input line is read. Note that
if filename cannot be read, it is treated as if it were an empty file, without
any error indication.
As a GNU sed extension, the special value /dev/stdin is supported for the file
name, which reads the contents of the standard input.
Por ejemplo
$ sed '1r content.txt' example.txt
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE