Unix One-liner To find If A File Is EmptySometimes, we face scenarios where we wish to take a action only if a file is empty. For example, we may like to populate some data in a file only when the file is empty.
Also, writing a script is always not feasible.
Being from an Informatica and Data warehousing platform, I often face this scenario. We can use the below one-liner command to find if a file is empty and populate data in it. The reason we want it to be a one-liner is that in Informatica pre/post session command we CANNOT use commands with multiple lines. So here is the one-liner:
[[ $(tr -d "\r\n" < filename.txt|wc -c) -eq 0 ]] && echo "dummy content in file" >> filename.txtExplanation:1. wc -c checks if the character count in file is zero (meaning file exists and it is empty)
2. && is UNIX equivalent for AND operation
3. The echo command then redirects ( >> ) the "dummy content in file" text to filename.txt
Published on July 23, 2014 06:24