我想在两个特定行之后将文本行插入到另一个文本文件中。
在类似的东西之后插入
some text...
example text
(
);
some text...
我有一个文本文件(包含两行文本),我希望 sed 将其插入到括号之间。
如果我尝试插入的文本文件包含类似下面的内容
need this;
in between the parentheses;
然后我希望结果看起来像这样
some text...
example text
(
need this;
in between the parentheses;
);
some text...
最好的解决方案是可行的(不必 sed)。
编辑澄清
在需要插入文本的部分之前还有其他左括号,例如
sometext...
sometext (sometext)....
sometext
(
);
exampletext
(
);
sometext...
因此,我认为需要引用“exampletext”才能查找括号。此外,它可能需要准确地搜索“exampletext”,因为文档中还有其他行带有“exampletextsometext ...”
完成此操作后,需要将添加到文件的内容保存在原始文件上。
最佳答案
如果打开的 (
单独在一行上,你可以这样做
sed -e '/^(/r fileToInsert' firstFile
因为 /^(/
找到了你要插入的行(“以左括号开头的行”),而 r
表示“读取内容文件并在此时插入。
如果确定插入点所需的表达式必须更复杂,请在评论中详细说明。例如,“完全是一个左括号,没有别的”将是 /^($/
编辑 感谢您澄清要求。如果您需要在 example text
之后插入此文本,后跟 (
,则以下脚本应该可以工作。将其放入自己的文件中,并使其可执行(chmod 755 myScript
),然后使用 ./myScript
运行。
#!/bin/bash
sed '
/exampletext/ {
N
/(/ r multi2.txt
}' multi1.txt
解释:
/exampletext/ { find a match of this text, then…
N go to the next line
/(/ match open parenthesis
r multi2.txt insert file 'multi2.txt' here
}' end of script
multi1.txt name of input file
请注意,这会将输出输出到 stdout
。您可以将其指向一个新的文件名 - 例如
./myScript > newFile.txt
我使用以下输入文件 (multi1.txt
) 对此进行了测试:
some text...
sometext...
sometext (sometext)....
exampletext
not the right string
(
);
sometext
(
);
exampletext
(
);
sometext...
它给出了输出
some text...
sometext...
sometext (sometext)....
exampletext
not the right string
(
);
sometext
(
);
exampletext
(
insert this
and that
);
sometext...
我认为这是您想要的?文本插入到 example text
后跟一个左括号的位置 - 但如果中间有另一行...
关于linux - sed命令在多行搜索后插入多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519848/