There are two basic errors in your code.
First:
Code:
read line file_name
Let's assume we do this from the CLI:
Code:
$ read line file_name
Hello World
$ echo $line
Hello
$ echo $file_name
World
$ read line file_name
This is a test
$ echo $line
This
$ echo $file_name
is a test
The
read command will assign the first field to the variable
line and the all other fields (separated by the IFS) to the variable
file_name.
There are several threads on the effects of the IFS on the read command. There's one by grail:
http://www.linuxquestions.org/questi....php?p=4664136.
To read a file line-by-line in a while loop, use:
Code:
while read line ; do
echo "$line"
done < file_name
Second:
Code:
echo "$c" > file_name
will overwrite the contents of
file_name with the contents of the variable
c. To append to the contents of a file using redirection, use
>>.
Code:
$ echo "Hello World" > file_name
$ cat file_name
Hello World
$ echo "Hello Earthlings" > file_name
$ cat file_name
Hello Earthlings
$ echo "From your Martian neighbours" >> file_name
$ cat file_name
Hello Earthlings
From your Martian neighbours
Of course, with the while loop, while you cannot read and write to the same file at the same time (as grail mentioned), you can redirect the while loop to also write to a new file. You can then copy the contents of the new file to file_name:
Code:
while read line ; do
echo "$line add this"
done < file_name > file_name.new
mv file_name.new file_name
Hope this helps.