我正在编写一个Bourne Shell脚本来自动编辑源文件。
我得到了我需要的行号:
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
现在我想在这个行号之后插入几行文字,我该怎么做?
答案 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