Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Change value from file inside a while

General Tech Bugs & Fixes

Max. 2000 characters
Replies

usr_profile.png

User

( 6 months ago )

I have a file like a database where I save name,surname,date of birth, gift, and I want to know if this person have got a gift from us or not. Those dates are splited by tabs in the file, one person per line, like:

name1  surname1  dateofbirth1  gift1
name2  surname2  dateofbirth2  gift2

Inside gift colum, I save "Yes" or "No" and my code looks like:

while IFS=$'\t' read -r name surname dob gift; do
    if [[ "$gift" == "No" ]]; then
        echo "Congrats, here is your gift
        gift=Yes
    fi
done < "file.txt"

But the gift colum, don't seems to change to yes, only seems to be there as an aux var. How can I change the value of that line, in that colum, to yes?

usr_profile.png

User

( 6 months ago )

 

Reading a value from a file and then changing the variable that holds that value will not change the value in the file.

Instead, you would have to detect what values need changing, change them, and then output the complete file (including modified values) to a new file. This new file can then be moved to the original name, replacing the old file.

Also, parsing text in the shell is generally to be avoided. Instead, consider using something like awkfor that:

awk -F '\t' 'BEGIN { OFS=FS }
             $4 == "No" { print "Congrats, here is your gift" >"/dev/stderr" }
             { $4 = "Yes"; print }' file.txt >newfile.txt

This would read through the file line by line and whenever the fourth column says No, it outputs the text Congrats, here is your gift.

Then, for every line, the fourth column is unconditionally set to Yes before the whole line is printed.

The way the program is written and run above, the Congrats... message will appear in the terminal (it's written to the standard error stream) while the updated contents of the file will be written to the new file called newfile.txt.

The BEGIN block at the start of the code simply sets the output field separator, OFS, to the same value as the input field separator, FS, which is set to a tab character on the command line using -F '\t'.

what's your interest


forum_ban8_5d8c5fd7cf6f7.gif