Home > Software engineering >  Using sed to replace symbol after semicolon
Using sed to replace symbol after semicolon

Time:09-28

Trying to make use of the sed command in order to change a word after a semicolon, like so (fileGrades.txt):

Student;Grade;Comment;
Eric;1;None;
Smith;2;None;
Thomas;1;None;
Chad;3;Nice work;

Now using sed command should find Eric and Chad and change both of their grades to 2, but leave the rest untouched. I was thinking of doing it with this method (see below), but it didn't work as it would not allow me to utilize the semicolon to know where to change the grade.

sed -i 's/Chad;*/Chad;2/g' fileGrades.txt

I also tried this method using wild cards such as *, ^ and . , but it didn't work.

CodePudding user response:

This is a tailor made problem for awk, use following awk code in your shown samples case.

awk 'BEGIN{FS=OFS=";"} FNR==1{print;next} $1=="Eric" || $1=="Chad"{$2=2} 1' Input_file

Once you are happy with above code's results then try following code to save output into Input_file itself.

awk 'BEGIN{FS=OFS=";"} FNR==1{print;next} $1=="Eric" || $1=="Chad"{$2=2} 1' Input_file > temp && mv temp Input_file

CodePudding user response:

You can use

sed -E -i 's/(Eric|Chad);[0-9]*/\1;2/g' fileGrades.txt

Details:

  • -E - POSIX ERE enabled
  • -i - the contents of the input file gets modified
  • s/(Eric|Chad);[0-9]*/\1;2 - matches and captures into Group 1 (\1) Eric or Chad, then matches ; and zero or more digits, and replaces this match with the Group 1 value, ; and 2.

See the online demo:

#!/bin/bash
s='Student;Grade;Comment;
Eric;1;None;
Smith;2;None;
Thomas;1;None;
Chad;3;Nice work;'
sed -E 's/(Eric|Chad);[0-9]*/\1;2/g' <<< "$s"

Output:

Student;Grade;Comment;
Eric;2;None;
Smith;2;None;
Thomas;1;None;
Chad;2;Nice work;
  • Related