ファイル内の改行で 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バージョンでは、 (read)コマンドを使用して、ファイルの内容を読み取り、指定された行アドレスに直接挿入する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

関連情報