0

I am trying to achieve this by redirecting the output to the same file but my file goes blank overtime. Things I tried:

  1. nl -s ') ' books > books
  2. nl -s ') ' books >> books in this case I am getting 2 copies of each line one numbered and the other non numbered
  3. nl -s ') ' < books > books
  4. cat books | nl -s ') ' > books

Rest other cases my input file is going blank. I do not wish to use a temporary file. How do I make changes to the same file while entering bash commands?

  • "How do I make changes to the same file while entering bash commands?" You can't. Use a temporary file, even if you don't like the idea. – rici Sep 03 '17 at 05:47
  • @rici so there is no way I can make changes to the same file? why? I am redirecting the output stream to the file itself. why is it going blank? can you provide me with an explanation? –  Sep 03 '17 at 05:50
  • 2
    Redirections are done by the shell before the command is executed. The `>` redirection operation opens the named file for writing, which empties the file if it exists or creates a new empty file if it doesn't. Only after that does the command execute, and by then the contents of the file have been deleted. – rici Sep 03 '17 at 05:51
  • See [this superuser question](https://superuser.com/questions/597244/why-does-redirecting-the-output-of-a-file-to-itself-produce-a-blank-file), and [this unix&linux question](https://unix.stackexchange.com/questions/110490/why-does-the-command-shuf-file-file-leave-an-empty-file-but-similar-commands). – Gordon Davisson Sep 03 '17 at 05:59
  • You can perform inplace edit using perl one liners `perl -pi.bak -e 's/^/$.) /g' books` – Kaushik Nayak Sep 03 '17 at 06:01
  • @KaushikNayak: You can also (somewhat more generally) use `sponge` if you happen to have it installed, but that and the `perl` solution are just ways to get someone to create the temporary file for you. – rici Sep 03 '17 at 06:05
  • Without tmp file: `echo 'x' | ex -s -c '% !nl -s ") "' books`, after the `)` you first see a double and than a single quote. – Walter A Sep 03 '17 at 09:41

0 Answers0