Bird
0
0

Why does the command sed 's/foo/bar/g' file.txt > file.txt often result in an empty file?

hard📝 Conceptual Q10 of 15
Linux CLI - Text Processing
Why does the command sed 's/foo/bar/g' file.txt > file.txt often result in an empty file?
ABecause sed deletes all lines containing 'foo'
BBecause redirecting output to the same file truncates it before sed reads
CBecause 'g' flag causes sed to remove lines
DBecause sed cannot write to files
Step-by-Step Solution
Solution:
  1. Step 1: Understand shell redirection behavior

    Redirecting output with '>' to the same file truncates the file immediately before sed reads it.
  2. Step 2: Effect on sed command

    Since the file is emptied before sed processes it, sed reads an empty file and writes nothing, resulting in an empty file.
  3. Final Answer:

    Because redirecting output to the same file truncates it before sed reads -> Option B
  4. Quick Check:

    Redirecting output to input file empties it before reading [OK]
Quick Trick: Avoid redirecting output to input file directly [OK]
Common Mistakes:
  • Thinking sed deletes lines with 'g' flag
  • Assuming sed cannot write files
  • Not realizing shell truncates file before command runs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Linux CLI Quizzes