我正在编写一个 Bourne Shell 脚本来自动编辑源文件。
我得到我需要的行号是这样的:
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
现在我想在这个行号之后插入几行文本,我该怎么做?
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
如果你安装了简单的 unix 编辑器ed
,你可以这样说:
echo "$line i
$lines
.
w
q
" | ed filename.txt
这是没有“视觉”模式的 vi。$line
必须是$lines
要插入文件的行号和文本。
看来你工作太辛苦了。为什么不直接插入文本而不是查找行号?例如:
$ sed '/#错误/a\ > 此文本已插入 > ' 测试.h
如果要插入的文本在文件中,则更容易:
$ sed '/#error/r 文件名' test.h
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
?
(更正)
你可以只使用 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