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

相关内容