linux - 将一个文件的一部分插入到另一个文件的特定位置

我正在尝试将一个文件的一部分复制到另一个文件的特定位置。

我不能使用 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 -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
}

https://stackoverflow.com/questions/73584480/

相关文章:

c++ - 在 C++ 中运行时获取变体中包含的类型?

list - Haskell:用关联列表中的给定键替换元素

ajax - Ajax 会降低性能吗?

php - OOP方式的蛋鸡问题

javascript - 单击按钮时不显示 Antd 模态

python - 将两个列表中的单个项目添加到新列表中

macos - macOS Ventura 中的终端重复

vba - 如何在 VBA 中处理对象声明(错误 91)

git - 错误 : unsupported value for gpg. 格式:ssh

haskell - xor = (/=) 是什么意思?