Thursday, October 6, 2022

[SOLVED] How to read a file and write in to another file using a shell script

Issue

I have a file which looks like this (file1.txt)

258.2222

I have to write this file1.txt value to another file. if there in no value in file1.txt then it should print as "Passed".

this is what I tried

for final in $(cat file1.txt);do
if [ "$final" ];then
        echo $final  > file2.txt
else
        echo "Passed" > file2.txt
fi
done

this only works with 1 scenario. if there is no value in file1.txt then it is not writing as "Passed"

expected output:

if there is a value in file1.txt:

258.2222

if there is no value (empty) in file1.txt:

Passed

Can someone help me to figure out this? Thanks in advance!

Note: I am not allowed to use general purpose scripting language (JavaScript, Python etc).


Solution

If file1.txt contains something (its file size is non-zero), you want that something to go into file2.txt:

if [ -s file1.txt ]; then
    cp file1.txt file2.txt
fi

If file1.txt is empty (or missing), then you want a line saying Passed written to file2.txt:

if [ -s file1.txt ]; then
    cp file1.txt file2.txt
else
    echo Passed >file2.txt
fi

If you want to avoid creating file2.txt if file1.txt is missing:

if [ -s file1.txt ]; then
    cp file1.txt file2.txt
elif [ -e file1.txt ]; then
    echo Passed >file2.txt
fi

The echo is now only executed if the -s test fails (the file does not exist, or it is empty) and -e test succeeds (the file exists).

At no point do you actually have to read the data from the file in a loop.



Answered By - Kusalananda
Answer Checked By - Marie Seifert (WPSolving Admin)