Search for and Replace Specific Data in a CSV File
Problem description & analysis
Below is text file inventory.csv:
cats,10,15
dogs,10,15
The three fields are name, value1, and value2. We are trying to locate the row containing corresponding name according to the input parameter replace, and replace the row with another input parameter replacer. If the first input parameter replace is cats and the second input parameter replacer is turtles,5,5, for instance, the desired result is as follows:
turtles,5,5
dogs,10,15
Solutions:
Solution 1: Through table sequence
Write the following script (p1.dfx) in esProc:
A |
|
1 |
=file("inventory.csv").import@c() |
2 |
=replacer.split@cp() |
3 |
>A1.iterate(if(#1==replacee,~.record(A2))) |
4 |
=file("result.csv").export@c(A1) |
Explanation:
Set two cellset parameters:
1. Parameter name: replacee Parameter value: cats
2. Parameter name: replacer Parameter value: turtles,5,5
A1 Import the csv file as a table sequence.
A2 Split parameter replacer into a sequence by comma.
A3 Find the record where value of the first column is equal to value of parameter replaceee, and populate members of A2’s sequence into fields of this record in order.
A4 Export the result table sequence A1 to result.csv.
Solution 2: Through a sequence of strings
Write the following script (p1.dfx) in esProc:
A |
|
1 |
=file("inventory.csv").read@n() |
2 |
>A1.run(if(~.split@c()(1)==replacee,~=replacer)) |
3 |
=file("result.csv").export(A1) |
Explanation:
A1 Read the CSV file as a sequence of strings, where each member is a row of the file.
A2 Loop through each member of A1, during which if value of the first member (the first column) of the current member (a string) separated by comma is equal to parameter replace, just replace the current member with parameter replacer.
A3 Export the result sequence of string after replacement to result.csv.
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL