Bourne Shell:如何将一些文本行插入文件的给定行号

时间:2010-04-22 16:56:51

标签: sed sh

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

我得到了我需要的行号:

line=`sed -n '/#error/=' test.h`
line=$[$line - 2]

现在我想在这个行号之后插入几行文字,我该怎么做?

5 个答案:

答案 0 :(得分:0)

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


(校正的)

答案 1 :(得分:0)

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

echo "$line i
$lines
.
w
q
" | ed filename.txt

这是没有“视觉”模式的vi。 $line必须是行号和$lines要插入文件的文本。

答案 2 :(得分:0)

你可以使用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

答案 3 :(得分:0)

line=$(sed -n '/#error/=' test.h)
line=$(($line - 2))
sed -i "$line s/$/\ntext-to-insert/" test.h

sed -i "$line r filename" test.h

答案 4 :(得分:0)

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

$ sed '/#error/a\
> this text is inserted
> ' test.h

如果要插入的文本位于文件中,则更容易:

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