我正在尝试将一个文件的一部分复制到另一个文件的特定位置。
我不能使用 sed -i '/match/r fileToInsert' file
因为我只想插入 fileToInsert 的部分内容,而不是整个文件。
我的 fileToInsert 如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- OriginalName: test.xml -->
<ListModes>
...
我试过这个:
sed -i "/match/a$(sed -n '2,3p' fileToInsert)" file
但它也不起作用,因为 fileToInsert 是一个 xml 文件,当遇到开头“<”时,sed 在第二行阻塞:
sed -e expression #1, char 59: unknown command: `<'
(如果我只尝试一行,它会起作用)。
有什么方法可以在 linux 上实现我想要的吗?可以与 sed、awk 或 redhat 发行版上的任何其他现有实用程序一起使用。
最佳答案
awk
可以在一条命令中完全做到这一点:
awk '
FNR == NR {
if (FNR >= 2 && FNR <= 3)
s = s $0 ORS
next
}
1
/match/ {
printf "%s", s
}' fileToInsert file
显示如下评论的find + awk
解决方案:
cat ins.awk
FNR == NR {
if (FNR >= 2 && FNR <= 3)
s = s $0 ORS
next
}
1
/match/ {
printf "%s", s
}
运行为:
find . -type f -exec awk -f ins.awk fileToInsert {} \;
更新:回应这条评论:
To be totally complete, if I wanted to insert only after the first match (or for the first nth matches), how would I do that please ?
您可以使用:
FNR == NR {
if (FNR >= 2 && FNR <= 3)
s = s $0 ORS
next
}
1
!done && /match/ {
printf "%s", s
++done
}
或者在第一个 MAX
匹配后插入,只将最后一个 block 更改为:
n <= MAX && /match/ {
printf "%s", s
++n
}
关于linux - 将一个文件的一部分插入到另一个文件的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73584480/