Wie kann man sed mit Zeilenumbrüchen in einer Datei arbeiten lassen?

Wie kann man sed mit Zeilenumbrüchen in einer Datei arbeiten lassen?

Ich passe mich andieses Skriptum den Inhalt einer Datei in eine andere Datei einzufügen. Das habe ich jetzt:

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

Ich führe es aus mit:./prepend.sh content.txt example.txt

Die content.txtDatei:

first_line
second_line

Die example.txtDatei:

REAL_FIRST_LINE
REAL_SECOND_LINE

Die Ausgabe des Skripts:

sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.

Und der Inhalt der example.txtDatei bleibt derselbe, obwohl ich ihn folgendermaßen haben möchte:

REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE

Antwort1

Es klingt, als ob Sie wollender rBefehl:

sed "1r $1" "$2"

Möglicherweise können Sie dies mit GNU sed tun:

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

Antwort2

In der GNU-Version von sedkönnen Sie den rBefehl (read) verwenden, um den Inhalt der Datei direkt an einer bestimmten Zeilenadresse zu lesen und einzufügen.

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.

Zum Beispiel

$ sed '1r content.txt' example.txt
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE

verwandte Informationen