Я адаптирую этот скрипт для вставки содержимого одного файла в другой файл. Вот что у меня есть:
#!/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
Файл example.txt
:
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
остается прежним, когда я хочу, чтобы оно было таким:
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
Это кажется, что Вы хотите r
команда :
sed "1r $1" "$2"
Вы могли бы быть в состоянии сделать это с GNU sed:
cat "$1" | sed '2r /dev/stdin' "$2"
В версии 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