Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add property _value pairs to a txt file and sort them alphabetically

Tags:

matlab

I want to add property-values pair in a txt file which contains property-values pairs and the properties should be sorted alphabetically, where a property is between square brackets and its value in the line below. This is an example file: On top of that i want to ignore the comment lines started with '#'.

#
[system]
# 
programming 
#
[information] 
#
application

Like:-

function [] = updateFile( fileName,property,propertyValue )

% all inputs in strings
%
rfh = fopen( fileName, 'r' ); % read handle
tname = tempname(); % temporary file name
wfh = fopen( tname, 'w' )

In this example, ´system´ is a property and ´programming´ its value. The same way, ´information´ is another property and ´application´ its value.

I want to call my function with a property-value pair and update the txt file with the new property-value pairs.

like image 564
bstar Avatar asked Dec 21 '25 16:12

bstar


1 Answers

Since you are updating a file you should open it in "append" mode. You use the sort function to sort your data. Assuming the variables property and propertyValue are cell arrays, your code would look something like this

function [] = updateFile( fileName,property,propertyValue )

% all inputs in strings

fid = fopen(fileName, 'a' ); % file handle
[property_sorted,sort_index] = sort(property); % sort file
for count = 1:length(sort_index)
    fprintf(fid,'%s\n%s\n',property_sorted(count),propertyValue(sort_index(count)));
end

fclose(fid);

See the documentation for sort (doc sort) for more information.

like image 197
Karthik V Avatar answered Dec 24 '25 09:12

Karthik V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!