Find string in file, replace everything after "="? - file

I would like to read a file, find some strings and replace everything that is after the symbol "=" in this line.
Lets say I have a textfile like this:
name=whatever
age=150
id.from.system=10298092_42_42
path=D:\name\somewhere
whatever_A= WHATEVER
Lets say I want to change path. At first I have to find the string "path" and then replace everything after "=" somehow. Any ideas? I know I could easily read the file line by line something like this:
val source = io.Source.fromFile("C:/myfile.txt)
val lines = source.mkString
source.close()
But this is maybe not the best idea, because its not that performant to read the whole file (maybe the file got 10000000 lines, and the string is already at line 2, but my program would read the whole file. That would be unnecessary).
And there is maybe another problem: if Im searching for specific strings, like here for "name" but these strings are there several times. I want to make sure that its only valid is after the string there is an "=". Maybe I could search always for something with an "=" at the end, that could solve the problem. But I have no idea how to write this in a nice scala code.

You can use an iterator to only iterate until you find the line you're looking for.
val source = io.Source.fromFile("somePath").getLines
val line = source.find(_.startsWith("path="))
line will contain the first line that starts with "path=".

If your C:/myfile.txt contains the line path=D:\name\somewhere, you can replace D:\name\somewhere with the following code:
val lines = fromString("path=D:\\name\\somewhere").getLines // use fromFile here
for { in <- lines
out <- if (in startsWith("path=")) "path=D:\\my\\path" else in
} yield out
This example will return the string
path=D:\my\path
You would need to use fromFile to get the lines and write the lines out to a new file.
Here's another approach that accomplishes the same thing:
val lines = fromString("path=D:\\name\\somewhere").getLines
lines.map(in => if (in startsWith("path=")) "path=D:\\my\\path" else in)

Related

Advice on reading multiple text files into an array with Ruby

I'm currently writing out a program in Ruby, which I'm fairly new at, and it requires multiple text files to be pushed into an array line by line.
I am currently unable to actually test my code since I'm at work and this is for personal use, but I'm seeking advice to see if my code is correct. I knows how to read a file and push it to the array. If possible can someone check it over and advise if I have the correct idea? I'm self taught regarding Ruby and have no-one to check my work.
I understand if this isn't the right place for trying to get this sort of advice and it's deleted/locked. Apologies if so.
contentsArray = []
Dir.glob('filepath').each do |filename|
next if File.directory?(filename)
r = File.open("#{path}#{filename}")
r.each_line { |line| contentsArray.push line}
end
I'm hoping this snippet will take the lines from multiple files in the same directory and stick them in the array so I can later splice what's in there.
Thank you for the question.
First let's assume that 'filepath' is something like the target pattern you want to glob in Dir.glob('filepath') (I used Dir.glob('src/*.h').each do |filename| in my test).
After that, File.open("#{path}#{filename}") prepends another path to the already complete path you'll have in filename.
And lastly, although this is probably not the problem, the code opens the file and never closes it. The IO object provides a readlines method that takes care of opening and closing the file for you.
Here's some working code that you can adapt:
contentsArray = []
Dir.glob('filepath').each do |filename|
next if File.directory?(filename)
lines = IO.readlines(filename)
contentsArray.concat(lines)
end
puts "#{contentsArray.length} LINES"
Here are references to the Ruby doc's for the IO::readlines and Array::concat methods used:
https://ruby-doc.org/core-2.5.5/IO.html#method-i-readlines
https://ruby-doc.org/core-2.5.5/Array.html#method-i-concat
As an alternative to using the goto (next) the code could conditionally execute on files, like this:
if File.file?(filename)
lines = IO.readlines(filename)
contentsArray.concat(lines)
end

how to retrieve specific value from file using Python

i have a text file which contain several lines in the end of the file I have the following line: "Total: 235267878"
my question is: How do I retrieve the specific value (235267878) and set it to a variable?
Thanks!
Since you didn't specify how long your file can be, we can iterate through the file:
with open('test.txt', 'r') as file:
for line in file:
if 'Total:' in line:
totalValue = line.split(':')[-1].strip()
print(totalValue)
In this solution I assume that the line we are looking for always has the form Total: {number}. We open the file in the read only mode and iterate through the lines (In my exmaple the file is called test.txt). After the line containing the total value is found, we split it and remove possible white spaces to get the number. The variable totalValue contains the number you are looking for.

Can i format output of matlab command such that i can use it to declare a new variable?

It's best explained with an easier example. Say some script in MATLAB gives me a cell array of strings:
temp = dir;
names = {temp.name}'
ans =
'folder1'
'folder2'
'file1'
I would like to use this output in another script, in another matlab session. Ideally, in the second script i would write
names = {'folder1', 'folder2', 'file1'}
but this means copypasting the output right under "ans = " and then manually adding the commas and curly brackets. In my case the cell array is quite large so this is undesirable. Even more it feels clumsy and there could be an easier way. Is there any way to make matlab print the output in such a way that i do not have to do this?
Exactly the same thing would be nice to know for matrices instead of cell arrays!!
I am aware of saving the variable in a .mat file and loading it, but i was wondering if the above is also possible (it would be cleaner in my case).
Personally I would advise the use of a cleaner way of handling this (such as mat files).
But then again sometimes the time spent setting these up is just not worth it for simple tasks which are unlikely to be repeated much...
For matrices there is a builtin function to do this, for cells however we would need produce a sting with the required format...
Matrix
For 1d or 2d matrices mat2str provides this functionality
mat2str(eye(2))
ans =
[1 0;0 1]
Cell
However to my knowledge there is no such builtin function for cells.
For a 1d cell array of strings the following will give the output in a copyable format:
['{',sprintf('''%s'' ',names{:}),'}']
ans =
{'folder1' 'folder2' 'file1' }
note: the stings in the cells cannot contain the ' character
If i understand you correctly, you are getting the names output from one script and want to use it within another script. Since you then cannot pass it as function argument, you are currently copying it over. One could do that with eval and copy&paste around:
names = {'folder1'
'folder2'
'file1'};
% create the command
n = length(names);
cmd = sprintf(['names = {',repmat('''%s'', ', 1, n-1) ,'''%s''}'], names{:}); % '%s, %s, ...., %s' format
% cmd contains the string: names_new = {'folder1', 'folder2', 'file1'}
% eval the cmd in script 2
eval(cmd) % evals the command names = {'folder1', 'folder2', 'file1'}
But this is generally very bad practice as it gets insanely hard to debug if something goes wrong somewhere. Also it makes you copy and paste things around, which i feel is uncomfortable. How about storing them in a txt file and loading them in the second script? It gets things done autmatically.
names = {'folder1'
'folder2'
'file1'};
% write output to file
fid = fopen('mynames.txt', 'w'); % open file to write something
fprintf(fid, [repmat('%s, ',1, n-1), '%s'], names{:});
fclose(fid);
% here comes script 2
fid = fopen('mynames.txt', 'r'); % open file to read something
names_loaded = textscan(fid, '%s');
names_loaded = names_loaded{:};
fclose(fid)
I think the key here is that you have a variable in 1 place, and want to use it in a different case.
In that situation you don't want to copy the output matlab generates, you just want to save the value itself.
After finding the result just do this:
save names
Later you can load this variable with
load names
Check doc save and doc names for more extensive examples. You may for example want to save all relevant variables in a file with a more generic name.

Writing multiline text files in Lua

I would like to know the best way to make my script write something into a file (lets say text.txt) in a way that would always add a line break at the end. When I append text using
file = io.open("test.txt", "a")
file:write("hello")
twice, the file looks like:
hellohello
But I want it to look like:
hello
hello
Unlike print, the new line character isn't added automatically when calling io.write, you can add it yourself:
file:write("hello", "\n")
The easiest way to achieve this would be to include a Newline character sequence every time you call the write method like so: file:write("hello\n") or so: file:write("hello", "\n"). This way, a script such as
file = io.open(test.txt, "a")
file:write("hello", "\n")
file:write("hello", "\n")
would result in the desired output:
hello
hello
There are, however, many other solutions to this (some being more elegant than the others). When outputting text in Java, for example, there are special methods such as BufferedWriter#newLine(), which will do the same thing in a more cleaner fashion. So if your interested in a different way of achieving this, I suggest you read up on the Lua docs for analogous methods/solutions.

How to find word from the end of file in Lua

Ok I use method from here: How to Read only the last line of a text file in Lua?
The problem is that sometimes line can be bigger.
The question is how can i find first word "foo" from the end of file and then use everything after it?
The problem is that sometimes line can be bigger.
Then you just need to seek further back from the end.
The question is how can i find first word "foo" from the end of file and then use everything after it?
Grab a big enough chunk of the file to be sure you've got the last foo, the use .*foo to skip everything up to and including the last "foo" (.* is greedy).
local f = io.open('filename', 'r')
f:seek('end', -1024)
local text = f:read('*a')
local after = string.match(text, ".*foo(.*)")
f:close()
If the file is not too big and you're ready to take the easy way out this might help:
fh=io.open('myfile.txt','rb')
str=fh:read'*a'
pat='foo'
afterFoo=str:match('.*'..pat..'(.*)$')
fh:close()
If you need a more complex, but faster (in run time on large files) solution, my guess would be that you' read in the file in chunks, reverse each of them, and look for your pattern in reverse. Don't forget to look for your pattern across the borders (the chunks must overlap at least the length of the pattern you're seeking in the general case).
For more explanation about the block reading, see my post here.

Resources