
estou me adaptandoeste roteiropara inserir o conteúdo de um arquivo em outro arquivo. Isto é o que tenho agora:
#!/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
Eu executo com:./prepend.sh content.txt example.txt
O content.txt
arquivo:
first_line
second_line
O example.txt
arquivo:
REAL_FIRST_LINE
REAL_SECOND_LINE
A saída do script:
sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.
E o conteúdo do example.txt
arquivo permanece o mesmo, quando eu quero que fique assim:
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
Responder1
Parece que você quero r
comando:
sed "1r $1" "$2"
Você pode fazer isso com o GNU sed:
cat "$1" | sed '2r /dev/stdin' "$2"
Responder2
Na versão GNU do sed
, você pode usar o r
comando (read) para ler e inserir o conteúdo do arquivo diretamente em um determinado endereço de linha
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 exemplo
$ sed '1r content.txt' example.txt
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE