如何使 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

相關內容