user2989371 user2989371 - 2 months ago 33
Bash Question

Replacing string in a specific position between known delimiters in shell

I have a file with data stored in this format


And I need to be able to find and replace a specific piece of data just knowing the ID and the position of the data using ';' as delimiters.

Kind of like the result of

grep -n "ID" [file] | cut -d ";" -f [position]

But replacing with a user given string instead of displaying

I reckon I need to use sed but nothing I've found has worked.

Edit: The user would come from a menu where they'd pick what to modify and provide the ID, they would then be prompted to type the replacement string and knowing the structure of the stored data (ID/Name/Surname/Country) the string would be replaced accordingly in the text file.


with awk:

echo 'ID;Data1;Data2;Data3' | awk -v id="ID" -v col=3 -v repl="foo" -F';' 'BEGIN{OFS=";";} $1==id {$col=repl;}1'