SQL-style Operations over TXT Files

Question

A txt file contains content like “Jack =5; Tom =4; Kelly =3;” I want to perform operations over a random record, like locate, add, delete and modify. The part on the left of the equal sign is unique and the part on the right of the equal sign is a non-unique number.

 

Answer

esProc can be used as Java’s class library. You can parse the formatted file as a two-dimensional table sequence, perform certain operations, and then output the result. Below is SPL script for doing this:

A

1

=file("E:\\file1.txt").read()

2

=A1.array@t(";").(~.array("=")).new(~(1):name,~(2):num)

3

=A2.pselect(name:"Tom")

4

=A2.insert@n(A3,"Kelly",8)

5

=A2.delete(3)

6

=A2(1).modify(7:num)

7

=A2.(name+"="+string(num)).concat(";")

8

=file("E:\\result.txt").write(A7)

 

A1: Read the txt file.

A2: Parse the file as a two-dimensional table sequence.

A3: Get the record where name value is “Tom” and return 2.

A4: Insert a record where name is “Kelly” and num is 8 at the positon of row 2.

A5: Delete row 3.

A6: Modify num value in row 1 into 7.

A7: Convert the modified table sequence into a string.

A8: Write A7’s result into E:\\result.txt.

Refer to How to Call an SPL Script in Java to learn more.