我正在编写一个Bourne Shell脚本来自动编辑源文件。Bourne Shell:如何在文件的给定行号处插入一些文本行
我得到的行号,我需要这样的:
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
现在我想,这个行号后插入文本的几行,我该怎么办呢?
我正在编写一个Bourne Shell脚本来自动编辑源文件。Bourne Shell:如何在文件的给定行号处插入一些文本行
我得到的行号,我需要这样的:
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
现在我想,这个行号后插入文本的几行,我该怎么办呢?
如果有简单的UNIX编辑器ed
安装,你可以说这样的事情:
echo "$line i
$lines
.
w
q
" | ed filename.txt
这是一个没有 “视觉” 模式VI。 $line
必须是行号和$lines
要插入文件的文本。
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
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
它看起来像你工作太辛苦。为什么不插入文本而不是找到行号?例如:
$ sed '/#error/a\ > this text is inserted > ' test.h
如果你想插入文本是在文件中,那就更简单了:
$ sed '/#error/r filename' test.h
无用的使用猫;-) – topskip 2010-04-22 17:43:36