Home > Back-end >  Why are the results of my bash command output differently depending on the name of my file?
Why are the results of my bash command output differently depending on the name of my file?

Time:10-10

I'm learning a bit of Bash and I'm playing around with different commands.

I created a file called lorem.txt where I've got lorem ipsum text.

I then used the following bash command

sed 's/[aAEOUIeouirtqzdnpms]//g' lorem.txt > randomfile.txt

to basically take the text in the lorem.txt file, remove all of the letters aEOUI etc. from the file, and output the result to a file called randomfile.txt.

This works great!

But when I change the code to

sed 's/[aAEOUIeouirtqzdnpms]//g' lorem.txt > lorem.txt

(Only having changed the name of the output file...) It doesn't work. Actually, the lorem.txt file goes blank. When I type cat lorem.txt, it's just empty. What is happening here? Why doesn't it just output the results and replace the text in the lorem.txt file with the output of the sed command?

CodePudding user response:

Because with the redirect (> lorem.txt) your system creates (and so empties) that file (lorem.txt) before running the command (sed ...), and this way your sed works on that empty file (since you passed lorem.txt to sed too).

Instead of redirecting, try using the -i option of sed for in-place editing. (Technically it writes to a temp file then overwrites the original in the end.)

sed -i 's/[aAEOUIeouirtqzdnpms]//g' lorem.txt

CodePudding user response:

The > will overwrite the file given, so lorem.txt in your case. Then sed will start.

You are looking for a inplace replacement, just use option -i:

sed -i 's/[aAEOUIeouirtqzdnpms]//g' lorem.txt

See also: sed edit file in place

  •  Tags:  
  • bash
  • Related