Yeste
Yeste

Reputation: 145

Find a line and modify it in a csv file given an input

I have a csv file with a list of workers and I wanna make an script for modify their work group given their ID's. Lines in CSV files are like this:

Before:

ID           TAG GROUP
niub16677500;B00;AB0

After:

ID           TAG GROUP
niub16677500;B00;BC0

How I can make this? I'm working with awk and sed commands but I couldn't get anything at the moment.

Upvotes: 0

Views: 729

Answers (2)

arturomieux
arturomieux

Reputation: 21

Sed can do it,

echo 'niub16677500;B00;AB0' | sed 's/\(^niub16677500;...;\)\(...\)$/\1BC0/'

will replace the AB0 group in your example with BC0, by matching the user name, semicolon, whatever 3 characters and another semicolon, and then matching the remaining 3 characters. Then as an output it repeats the first match with \1 and adds BC0.

You can use :

sed 's/\(^niub16677500;...;\)\(...\)$/\1BC0/' <old_file >new_file

to make a new_file with this change.

https://www.grymoire.com/Unix/Sed.html is a great resource, you should take a look at it.

Upvotes: 0

Allan
Allan

Reputation: 12438

With awk:

awk -F';' -v OFS=';' -v id="niub16677500" -v new_group="BC0" '{if($1==id)$3=new_group}1' input.csv
ID;TAG;GROUP
niub16677500;B00;BC0

Redirect the output to a file and note that the csv header should use the same field separator as the body.

Explanations:

  • -F';' to have input field separator as ;
  • -v OFS=';' same for the output FS
  • -v id="niub16677500" -v new_group="BC0" define the variables that you are going to use in the awk commands
  • '{if($1==id)$3=new_group}1' when the first column is equal to the value contained in variable id the overwrite the 3rd field and print the line

With sed:

id="niub16677500"; new_group="BC0"; sed "/^$id/s/;[^;]*$/;$new_group/" input.csv 
ID;TAG;GROUP
niub16677500;B00;BC0

You can either do an inline change using -i.bak option, or redirect the output to a file.

Explanations:

  • Store the values in 2 variables
  • /^$id/ when you reach a line that starts with the ID store in the variable id, run sed search and replace
  • s/;[^;]*$/;$new_group/ search and replace command that will replace the last field by the new value

Upvotes: 2

Related Questions