Bird
0
0

You want to combine file I/O with conditional logic: Write a script that reads numbers from nums.txt and writes only even numbers to evens.txt. Which script snippet correctly does this?

hard🚀 Application Q9 of 15
Bash Scripting - File Operations in Scripts
You want to combine file I/O with conditional logic: Write a script that reads numbers from nums.txt and writes only even numbers to evens.txt. Which script snippet correctly does this?
Awhile read n; do if (( n % 2 == 0 )); then echo $n >> evens.txt; fi; done < nums.txt
Bfor n in $(cat nums.txt); do echo $n >> evens.txt; done
Ccat nums.txt | grep even > evens.txt
Decho $(cat nums.txt) > evens.txt
Step-by-Step Solution
Solution:
  1. Step 1: Read numbers line by line from nums.txt

    Using 'while read' safely processes each number.
  2. Step 2: Use arithmetic condition to check even numbers

    The condition (( n % 2 == 0 )) filters even numbers.
  3. Step 3: Append even numbers to evens.txt

    Using >> inside the if block adds only even numbers.
  4. Final Answer:

    while read n; do if (( n % 2 == 0 )); then echo $n >> evens.txt; fi; done < nums.txt -> Option A
  5. Quick Check:

    Combine file read and condition to filter output [OK]
Quick Trick: Use while read and if condition to filter file lines [OK]
Common Mistakes:
MISTAKES
  • Appending all numbers without filtering
  • Using grep incorrectly for even numbers
  • Overwriting file inside loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes