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.
If your C:/myfile.txt contains the line
path=D:\name\somewhere, you can replaceD:\name\somewherewith the following code:This example will return the string
You would need to use
fromFileto get the lines and write the lines out to a new file.Here’s another approach that accomplishes the same thing: