views:

160

answers:

5

I'm writing a Bourne Shell script to automatically edit a source file.

I get the line number I need like this:

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

Now I want to insert a few lines of text after this line number, how can I do this?

A: 
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

?
(corrected)

Vlad
useless use of cat ;-)
Patrick
A: 

If you have the simple unix editor ed installed, you can say something like this:

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

This is vi without the "visual" mode. $line must be the line number and $lines the text to insert into the file.

Patrick
A: 

you can just use 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
ghostdog74
A: 
line=$(sed -n '/#error/=' test.h)
line=$(($line - 2))
sed -i "$line s/$/\ntext-to-insert/" test.h

or

sed -i "$line r filename" test.h
Dennis Williamson
A: 

It looks like you're working too hard. Why not just insert the text instead of finding the line number? eg:

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

If the text you want to insert is in a file, it's even easier:

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