Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Adding text to the beginning of a file



On 17/03/07, Dave M G <martin@example.com> wrote:
Arwyn,

Thanks for responding.
> Sed is your friend:
> sed '1,/^#--/ d' < file_with_data_to_replace > tmp_file
> cat file_with_new_data tmp_file > end_result_file

Thank you for the code and the link. I'm afraid that the tutorial left
my head spinning a bit. I'm just learning bash shell syntax, and sed
seems to have a whole new layer of options. I hope it's okay if I ask
some more questions.

What I've learned is that this line in the above code:
cat file_with_new_data tmp_file > end_result_file

... wipes out the whole tmp_file with the contents of file_with_new_data.

If I change it to:
cat file_with_new_data tmp_file >> end_result_file

... then it adds the contents of file_with_new_data to the *end* of
tmp_file. This is better, but actually, what I want to do is stick the
data on at the beginning. Prepend, not append. I looked up command
options for "cat" but couldn't find how to do it.


The '>' pipe does wipe the contents of the file, but only at the start of the pipe. In other words #> cat file1 file2 > result is functionally the equivalent of #> cat file1 > result #> cat file2 >> result which is actually what you want.


Other questions:

1. Can I use cat to prepend the contents of a variable in the shell
script? I tried this:
TEXT="This is text"
cat $TEXT temp.file >> new.file

... but what it tried to do was look for three files called "This",
"is", and "text" to append to the new file.

cat is for files, echo is for text and variables. The following
command should do what you want:
#> TEXT="This is text"
#> echo $TEXT | cat - temp.file > new.file

The '-' represents the standard input. In this case data received from
the '|' pipe.

2. How do I execute this on multiple files? Like *.php, and .class?
By using a loop. Providing your files have no spaces in their names
you might find the for loop useful:
#> for file in `ls`; do
#>   echo "this gets added to the start of each file in the directory"
| cat - $file > tmp
#>   mv tmp $file
#> done

Note that the for loop will iterate over a list of words delimited by
spaces, so if you have spaces in your file names the above won't work.
I use an ugly hack to get it to work, but I suspect someone else knows
a much more elegant way of doing it, so I'm not going to post the
hack.

Arwyn


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links