Я адаптирую этот скрипт для вставки содержимого одного файла в другой файл. Это то, что у меня есть сейчас:
#!/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
Я запускаю его с помощью: ./prepend.sh content.txt example.txt
Файл content.txt:
first_line
second_line
Кнопка [ f8] file:
REAL_FIRST_LINE
REAL_SECOND_LINE
Выход скрипта:
sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.
И содержимое файла example.txt остается таким же, когда я хочу, чтобы он был таким: [ ! d6]
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
В версии GNU sed вы можете использовать команду r (чтение) для чтения и вставки содержимого файла непосредственно на заданный адрес строки
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.
Например
$ sed '1r content.txt' example.txt
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE