file question

without using a file stream editor such as sed, is there a way to echo the value of a variable to a specific location in a file (i.e. if the file has 20 lines, can I add a new line with the contents of the variable FOO at line 1?) ? I should add that the file will be created during run time. The shell will create the file, capture a output from a spool command, then slap a header record and trailer record on it. The header cannot be initially created because its dependant upon the output of the spool.

You could do something like this:

echo "HEADER" > tmpfile.txt
cat logfile.txt >> tmpfile.txt
mv tmpfile.txt logfile.txt

Why not use sed?

I was more curious than anything as to whether there is a way to insert a line of data into a file (at any given line number) without using an editor such as sed.

What I really would like to know is if I can accomplish this without using intermediate files such as noted by the first reply.

How can I do this with sed?

Unfortunately sed requires the use of temporary files as you can't output to the original file, so either way you're going to have to use temp files.

See this thread for the sed syntax on inserting. Note in the examples 1 is used for the insert, but you can specify the line number as different.

If you depend on the line numbers for the insertion,
probably the easiest way is to use awk (nawk).

awk '
# Insert line in the file before line 5
NR=5 { print"The line you need"}
{print}
' infile > outfile

What about using the shell?

This will take whatever is in "file1", and place a seperator line before line 5:

#! /bin/ksh

integer n=1
while read line; do
 (( n == 5 )) && { print "#------- Seperator ------#"; }
 print $line
 n=n+1
done < file1

Just the speed. If input files will be thousands of lines or more
difference will be very significant .:wink: