Assign Values to a Variable in While Loop and Update the File

Hello,

Could anyone please help me with Assigning a value to variable and then updating the value in the original file

IFS='|'
while read -r Serial_ID JOB_NAME STATUS 
do
if [ "$STATUS" = "" ]
then 
echo "Perform Fuctions"
???Assign STATUS to COMPLETED and Update File???    
done <File

Show the input you have and show the output you want.

On a hunch, perhaps something like:

while IFS="|" read -r SERIAL JOB STATUS
do
        if [ condition ] 
        then
                STATUS="somethingelse"
        fi
        printf "%s|%s|%s\n" "$SERIAL" "$JOB" "$STATUS"
done < inputfile > outputfile

Note that inputfile and outputfile can't be the same.

Not sure I entirely understand, but

STATUS=COMPLETED
printf "%s%s%s%s%s\n" "$Serial_ID" $IFS "$JOB_NAME" $IFS "$STATUS" >> file2

and rename file2 to FIle after the loop?

Process the ones which have null in the 3rd column and then update the 3rd column in the file as COMPLETED

Input

123|ABC|
456|PQR|COMPLETED
111|XYZ|
121|ASD|COMPLETED

Output

123|ABC|COMPLETED
456|PQR|COMPLETED
111|XYZ|COMPLETED
121|ASD|COMPLETED

---------- Post updated at 03:49 PM ---------- Previous update was at 03:46 PM ----------

I need to use the same file and update the row in the file by assigning Completed in the 3rd column after i perform some functions

You cannot.

Not with standard text files.

Files do not work that way. Even something like sed -i really just replaces or overwrites the entire file.

So I think my method should work:

cp inputfile inputfile.bak
while IFS="|" read -r SERIAL JOB STATUS
do
        if [ -z "$STATUS" ] 
        then
                do_something
                STATUS="somethingelse"
        fi
        printf "%s|%s|%s\n" "$SERIAL" "$JOB" "$STATUS"
done < inputfile > outputfile

mv outputfile inputfile
1 Like

Thank You So much Corona, i guess this should be good enough for me and meets my requirement