如何将数字从 X 到 Y 的行插入到 Z 行之后的另一个文件中?

Apo*_*tle 7 sed awk text-processing

我创建了两个文件:

echo -e "1\n2\n3\n4\n5" > 123.txt
echo -e "a\nb\nc\nd\ne" > abc.txt
Run Code Online (Sandbox Code Playgroud)

我想获取123.txt包含以下内容的文件:

1
2
3
b
c
d
4
5
Run Code Online (Sandbox Code Playgroud)

因此,换句话说,将文件中编号为 2 到 4 的行插入abc.txt到文件中123.txt的第三行之后。

我在这里查看了许多类似的问题,但没有找到合适的答案。尽管如此,我还是得到了以下几行:

sed -n '2,4p' abc.txt
Run Code Online (Sandbox Code Playgroud)

并在第三行之后将一些文本放入文件中:

sed -i '3a\mytext' 123.txt
Run Code Online (Sandbox Code Playgroud)

如何使用上一个命令 stdout 或/和sed/awk单个命令执行此操作?

ste*_*ver 6

如果您的系统有 GNU 版本sed,则可以使用 GNU 扩展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. 
Run Code Online (Sandbox Code Playgroud)

例如,

$ sed '3r /dev/stdin' 123.txt < <(sed -n '2,4p' abc.txt)
1
2
3
b
c
d
4
5
Run Code Online (Sandbox Code Playgroud)

  • `r` 命令在 POSIX 中。sed 部分中唯一不是 POSIX(但即使在非 GNU 系统上也很常见)的是 `/dev/stdin`。如果您使用管道而不是命令替换,则除了存在 `/dev/stdin` 的要求之外,您的 shell 代码段是 POSIX。 (2认同)