首页 > 解决方案 > 如何将长文本附加到 bash 中的特定行?

问题描述

我有一个 bash 脚本,可以复制和粘贴一个 txt 文件(T1,T2..T100)一百次。我需要在该文本文件的 txt 文件的第 454 行附加特定的代码行。

我尝试使用 sed 和 awk 但它们似乎不能正常工作。

我试图做这样的事情,但没有奏效:

awk 'NR==454{print "try:
  Mesh_1.ExportMED( r'/home/students/gbroilo/Desktop/Script/Mesh_1.med', 0, SMESH.MED_V2_2, 1, None ,1)
  pass
except:
  print 'ExportToMEDX() failed. Invalid file name?'"}1'

标签: bashawksedappendsubstitution

解决方案


这可能对您有用(GNU sed):

sed -i '454a\line one with a quote '\''\n'\''another'\''\nlast line' fileT*

另一种方式:

cat <<\!>fileInsert
line one with a quote '
'another'
last line
!
sed -i '454r fileInsert' fileT*

完后还有:

cat <<\! | sed -i '454r /dev/stdin' fileT*
line one with a quote '
'another'
last line
!

如果要将特定文本插入特定文件,请使用 GNU 并行,如下所示:

parallel -q sed -i '/454r fileInsert{}' fileT{} ::: {1..100}

推荐阅读