ソースファイルを自動的に編集するBourneシェルスクリプトを書いています。
必要な行番号を次のように取得します。
line=`sed -n '/#error/=' test.h`
line=$[$line - 2]
この行番号の後に数行のテキストを挿入したいのですが、どうすればよいですか?
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
がインストールされている場合は、次のように言うことができます。
echo "$line i
$lines
.
w
q
" | ed filename.txt
これは「ビジュアル」モードのないviです。ファイルに挿入する$line
行番号とテキストである必要があります。$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
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 \ >このテキストが挿入されます >'test.h
挿入するテキストがファイルにある場合は、さらに簡単です。
$ sed'/#error / r filename' test.h