Как заставить sed работать с переносами строк в файле?

Как заставить sed работать с переносами строк в файле?

Я приспосабливаюсьэтот сценарийвставить содержимое одного файла в другой файл. Вот что у меня сейчас:

#!/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

решение1

Звучит так, как будто ты хочешькомандаr:

sed "1r $1" "$2"

Это можно сделать с помощью GNU sed:

cat "$1" | sed '2r /dev/stdin' "$2"

решение2

В версии GNU sedвы можете использовать rкоманду (read) для чтения и вставки содержимого файла непосредственно по указанному адресу строки.

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

Связанный контент