comearound
comearound

Reputation: 155

script only outputting one file name of many to new file

I am trying to output the name of every file that in it's last line has "#FIXME" into a new file.

find -type f -print0 |while IFS= read -rd '' file; do
tail -n1 "$file" | grep -q FIXME && echo "$file" > newlog.log 
done  

This only outputs one file containing "#FIXME" to newlog.log when there are actually mutliple files.
Could anyone tell me what is going wrong?

Upvotes: 1

Views: 45

Answers (2)

Yunnosch
Yunnosch

Reputation: 26703

You have setup a loop which executes this line in the middle for many files:

tail -n1 "$file" | grep -q FIXME && echo "$file" > newlog.log

This line however creates and writes the file "newlog.log" each time,
which results in the already existing content being overwritten each time, with only one file name. This gave you the impression that only one file name was written to the log file. It happens to be the last one.

In order to get a list of all the written file names, i.e. to keep all of the content, you need to append to the existing loggile, instead of overwriting it.
To do that, use >> instead of >.

tail -n1 "$file" | grep -q FIXME && echo "$file" >> newlog.log

This creates the need to consider the content of the log file before executing the script.
Either you are fine with always also keeping the content of the previous script execution, which I guess you are probably not, or you can make sure the file has no content.

You can either delete the file and create it freshly. Or you do once use the > intentionally. This would allow you to make something of a headline for the list, e.g. containing the date of the creation and the path you executed it in.

Upvotes: 2

Romeo Ninov
Romeo Ninov

Reputation: 7225

You need to append to the file, not overwrite. ANd this

tail -n1 "$file" | grep -q FIXME && echo "$file" > newlog.log 

should be

tail -n1 "$file" | grep -q FIXME && echo "$file" >> newlog.log 

Upvotes: 1

Related Questions