0

This should be a simple fix but I cannot wrap my head around it at the moment.

I have a comma-delimited file called my_course that contains a list of courses with some information about them.

I need to get user input about the last two fields and change them accordingly.

Each field is constructed like: CourseNumber,CourseTitle,CreditHours,Status,Grade

Example file:

CSC3210,COMPUTER ORG & PROGRAMMING,3,0,N/A
CSC2010,INTRO TO COMPUTER SCIENCE,3,0,N/A
CSC1010,COMPUTERS & APPLICATIONS,3,0,N/A

I get the user input for 3 things: Course Number, Status (0 or 1), and Grade (A,B,C,N/A)

So far I have tried matching the line containing the course number and changing the last two fields. I haven't been about to figure out how to modify the last two fields using sed so I'm using this horrible jumble of awk and sed:

temporary=$(awk -v status=$status -v grade=$grade '
BEGIN { FS="," }; $(NF)=""; $(NF-1)="";
/'$cNum'/ {printf $0","status","grade;}'  my_course)

sed -i "s/CSC$cNum.*/$temporary/g" my_course

The issue that I'm running into here is the number of fields in the course title can range from 1 to 4 so I can't just easily print the first n fields. I've tried removing the last two fields and appending the new values for status and grade but that isn't working for me.

Note: I have already done checks to ensure that the user inputs valid data.

2 Answers 2

1

Use a simple awk-script:

BEGIN {
  FS=","
  OFS=FS
}

$0 ~ course {
  $(NF-1)=status
  $NF=grade
} {print}

and on the cmd-line, set three parameters for the various parameters like course, status and grade.

in action:

$ cat input
CSC3210,COMPUTER ORG & PROGRAMMING,3,0,N/A
CSC2010,INTRO TO COMPUTER SCIENCE,3,0,N/A
CSC1010,COMPUTERS & APPLICATIONS,3,0,N/A

$ awk -vcourse="CSC3210" -vstatus="1" -vgrade="A" -f grades.awk input
CSC3210,COMPUTER ORG & PROGRAMMING,3,1,A
CSC2010,INTRO TO COMPUTER SCIENCE,3,0,N/A
CSC1010,COMPUTERS & APPLICATIONS,3,0,N/A

$ awk -vcourse="CSC1010" -vstatus="1" -vgrade="B" -f grades.awk input
CSC3210,COMPUTER ORG & PROGRAMMING,3,0,N/A
CSC2010,INTRO TO COMPUTER SCIENCE,3,0,N/A
CSC1010,COMPUTERS & APPLICATIONS,3,1,B
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the answer but don't use all-upper-case for your variable names - that's for builtin variables like NR, OFS, FILENAME, etc.
0

It doesn't matter how much commas you have in course name as long as you look only at last two commas: sed -i "/CSC$cNum/ s/.,[^,]*$$/$status,$grade/" The trick is to use $ in pattern to match the end of line. $$ because of double quotes.

And don't bother building the "temporary" line - apply substitution only to line that matches course number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.