Adding Text To Middle Of File

Hi I am trying to write a bash script to add a line of text to the middle of a file.

The way I worked it out was to calculate the number of lines and divide by 2. The file I am using is called newfile and it just contains lines of data.

The new file I have created I have called midfile and the line of text which will be added is called myline.

code I have done so far is below:

#!/bin/bash
 
num=$(((wc -l $newfile)/2))
 
cat newfile | head -$num > midfile
cat myline >> midfile
cat newfile | tail -$num >> midfile

At the moment the new file is created but it only contains the line which is supposed to go in the middle. Im guessing the mistake I have made is simple but can't seem to figure out where I have gone wrong. Many Thanks in Advance.

check the output/error of this command. I think you will get syntex error.

try this:

num=$(expr $(wc -l < $newfile) / 2)

Try:

num=$(($(wc -l<newfile)/2))

Thanks Scrutinizer.....that is working great.....can u briefly explain why you add a < so i can understand......am a new starter :rolleyes:

Hi, if you use < then the wc command leaves out the file name.

you can check by own.

/home->wc -l file
11 file
/home->wc -l < file
11
/home->

"<" is the indirection, which is sending file o/p to the command line by line.
as a result of that, you will get the line count only. ( unlikely the filename also which you get in the another command.)

if you use first command than you will have to suppress the filename part.

Thanks, I tried that and it makes sense now.....

Was thinking....would separating the filename in brackets allow you to not include the filename??

Didn't get you what you are trying to say..
please show by typing the command.