2

I googled this command but there was not.

grep -m 1 "\[{" xxx.txt > xxx.txt

However I typed this command, error didn't occured. Actually, there was not also result of this command.

Please anyone explain me this command's working?

Choi
  • 483
  • 1
  • 3
  • 15
  • 1
    The `xxx.txt > xxx.txt` part means `xxx.txt` is empty by the time `grep` reads it. – Jonathan Leffler Jun 04 '18 at 07:34
  • 1
    The `-m 1` option means 'stop after 1 match', but given that the file is empty, there won't be any matches anyway. – Jonathan Leffler Jun 04 '18 at 07:35
  • Possible duplicate of [Problem with Bash output redirection](https://stackoverflow.com/questions/123235/problem-with-bash-output-redirection) – l0b0 Jun 04 '18 at 08:35
  • [One of many duplicates](https://superuser.com/questions/597244/why-does-redirecting-the-output-of-a-file-to-itself-produce-a-blank-file) – l0b0 Jun 04 '18 at 08:36
  • https://explainshell.com/explain?cmd=grep+-m+1+%22%5C%5B%7B%22+xxx.txt – Biffen Jun 04 '18 at 09:17

1 Answers1

1

This command reads from and writes to the same file, but not in a left-to-right fashion. In fact > xxx.txt runs first, emptying the file before the grep command starts reading it. Therefore there is no output. You can fix this by storing the result in a temporary file and then renaming that file to the original name.

PS: Some commands, like sed, have an output file option which works around this issue by not relying on shell redirects.

l0b0
  • 55,365
  • 30
  • 138
  • 223