How can I write changes into file

content =!(file.txt)

 |> String.split("\n", trim: true)
 |> List.first()
 |> String.split
 |> List.replace_at(-1, variable)

Welcome to the forum!

Can you please use triple backticks (```) before and after your code block so it gets nicely formatted?

Additionally, what have you tried so far?


File.write/3 is the most obvious answer.

To get a more meaningful answer, you might try to ask a more meaningful question.


Contents of file.txt:

abc def old_value

A code sample:

file_name = "file.txt"
data = "new_value"

content =!(file_name)
[head | tail] = String.split(content, "\n", trim: true)
new_head = head |> String.split(" ") |> List.replace_at(-1, data) |> Enum.join(" ")
new_content = Enum.join([new_head | tail], "\n")
File.write(file_name, new_content)

Result in file.txt:

abc def new_value

This is the train of thought i never took, thanks a load, using the [head | tail] and Enum.join to restore the list properties and maintain the file view. though there are a iterations were there is

has caused a few strings to “join” a new line.

Thanks for the tip, I did realise my question is blunt will work on that.
Thought there was a way to manipulate the file directly, without having to overwrite the whole file

Thanks will definitely use it in future.

EDIT: Missed the List.first(), the code doesn’t do what’s needed.

While what @Eiji showed you will work I’d prefer something a bit more readable (subjective, of course):

changed_contents =!("file.txt")
  |> String.split("\n", trim: true)
  |> List.first()
  |> String.split
  |> List.replace_at(-1, variable)

File.write("file.txt", changed_contents)

Mind you, this will only change the last line in the file but maybe that’s what you wanted.

There is no way to manipulate the file directly without opening/loading it first.

wanted to change the last value on the first line of the file.

Implementing the above code actually over writing the whole file with the only that one line.

Ah, there was a List.first() there, didn’t look carefully.

Here’s code that does what you want:

new_value = "<value>"
path = "<somewhere>"
separator = " "

[first | rest ] =!(path)
  |> String.split("\n", trim: true)

changed_first =
  |> String.split()
  |> List.replace_at(-1, new_value)
  |> Enum.join(separator)

changed_contents =
  [changed_first | rest]
  |> Enum.join("\n")

File.write!(path, changed_contents)

It’s a pretty naive implementation just to demonstrate the flow though, you might want to optimize it.

If you only want to change the first line in a file I’d look into the normal UNIX command-line tools. Using a full-blown programming language for something like that could be an overkill. But it depends if your need is illustrative or it’s more complex in your production code.