Skip to content
Advertisement

get user input in awk script and update it in file

I have a students.txt (RollNo, Name, IDU, CGPA), If Roll number exists prompt the user to change the IDU and CGPA and update the same in the file named “Student.txt”

I made the following script:

    #! /bin/bash

    dispaly(){
      awk -F ":" -v roll=$1 '{ if ( $1 == roll) {name = $2; print name; } } 
                             END {if (name == "") print "not found" }' students.txt       
    }

    echo "Enter the roll no."
    read rno

    if [ $rno -ge 1000 ] && [ $rno -le 9999 ]
    then
       dispaly $rno
       # Now I have a valid $rno and want to update that line
    else
       echo Enter no between 1000 and 9999
    fi

now I need help in taking user input for IDU and CGPA values and update the students.text file with that values against the record found.

Advertisement

Answer

first, I grep for roll

grep ^roll students.txt 

if found then used awk to replace the records

awk  -F : -v rno=$rno -v idu=$idu -v cgpa=$cgpa ' $1==rno { $3=idu;$4=cgpa} OFS=":" ' students.txt > tmp.txt && mv tmp.txt students.txt
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement