Sdout stream a command into the same file?


New Member
I do not know if I expressed myself well in the title, but please correct me if I am wrong.
Here I have a beginner problem:
I have a file with multiple lines of code, and I can number lines of code with nl command, now I want to number the lines but i want to stream the output into the same file.
So that when I open my file I will have lines numbered
For example I tried doing it this way: nl myfile.txt > myfile.txt
And then I tried sending it into a different file( nl myfile.txt > secondfile.txt) and saw that worked, so I do not understand why I cant output nl into the same file.
I also tried piping nl into the echo command like this: echo > myfile.txt | nl myfile.txt

Can someone please explain me why this doesnt't work, I am still relatively a begginer.

Thank You in advance,
Lukas Unix


Well-Known Member
No, that is correct behaviour. You need to redirect the output to a new file. That's just the way that nl works.

The best way of overwriting the original file is to do something like this:
nl myfile.txt > temporary.txt && mv temporary.txt myfile.txt
The above uses nl to create a file called temporary.txt using the content of myfile.
Then we rename temporary.txt to myfile.txt. Effectively overwriting the original file.

I've never ran nl with the intention of modifying the original file. I've only ever used it to format/import code into another document with line numbers.

For example, If I was writing a tex document using vim and I wanted to import code from somefile.cpp - from inside vim, I'd issue the command:
:r !nl /path/to/somefile.cpp
And that would run nl in a terminal to number the lines of code in somefile.cpp and read the numbered output into the current document, without affecting somefile.cpp.


New Member
Here's why nl myfile > myfile doesn't work. The shell (bash) is reading and processing your commands as you enter them. It sees your nl command and sees that you want the output to go into myfile so it opens myfile for output. This deletes any existing contents and gets the file ready to receive data.

Then the shell starts nl and nl wants to read myfile. But now myfile is empty so there's nothing to do and it quits.

Members online

Latest posts