Sed BourneShell:如何在文件的给定行号中插入一些文本行

Sed BourneShell:如何在文件的给定行号中插入一些文本行,sed,sh,Sed,Sh,我正在编写一个Bourne Shell脚本来自动编辑源文件 我得到了我需要的行号,如下所示: line=`sed -n '/#error/=' test.h` line=$[$line - 2] echo "$line i $lines . w q " | ed filename.txt 现在我想在这个行号后面插入几行文字,我该怎么做 totallines=`cat test.h | wc -l` head -n $line test.h >$$.h echo "some text"

我正在编写一个Bourne Shell脚本来自动编辑源文件

我得到了我需要的行号,如下所示:

line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
echo "$line i
$lines
.
w
q
" | ed filename.txt
现在我想在这个行号后面插入几行文字,我该怎么做

totallines=`cat test.h | wc -l`
head -n $line test.h >$$.h
echo "some text" >>$$.h
tail -n $((totallines-line)) test.h >>$$.h
mv $$.h head.h
??
更正

如果安装了简单unix编辑器ed,可以这样说:

line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
echo "$line i
$lines
.
w
q
" | ed filename.txt
这是没有视觉模式的vi$行必须是行号,$lines是要插入文件的文本。

您可以使用awk

awk '/#error/{for(i=1;i<=NR-2;i++){print _[i]}print "new\n"_[NR-1];f=1 }!f{_[NR]=$0 }f' file > t && mv t file


看来你工作太辛苦了。为什么不直接插入文本而不是查找行号?例如:

$ sed '/#error/a\ > this text is inserted > ' test.h 如果要插入的文本位于文件中,则更容易:

$ sed '/#error/r filename' test.h