0
0
Bash Scriptingscripting~10 mins

Reading files line by line (while read) in Bash Scripting - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to read a file line by line using a while loop.

Bash Scripting
while [1] read line; do
  echo "$line"
done < file.txt
Drag options to blanks, or click blank then click option'
Ado
Bcat
CIFS=
Dfor
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'for' loop instead of 'while' to read lines
Not setting IFS, causing trimming of spaces
Using 'cat' incorrectly inside the while loop
2fill in blank
medium

Complete the code to read a file named 'data.txt' line by line and print each line.

Bash Scripting
while IFS= read [1]; do
  echo "$line"
done < data.txt
Drag options to blanks, or click blank then click option'
Atext
Bline
Cfile
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names that do not match the echo statement
Using reserved words as variable names
3fill in blank
hard

Fix the error in the code to correctly read lines from 'input.txt'.

Bash Scripting
while IFS= read line; do
  echo "$line"
done < [1]
Drag options to blanks, or click blank then click option'
Ainput.txt
Bfile.txt
Coutput.txt
Ddata.txt
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong filename in the input redirection
Missing the '<' symbol before the filename
4fill in blank
hard

Fill both blanks to read 'myfile.txt' line by line and count lines longer than 5 characters.

Bash Scripting
count=0
while [1] read line; do
  if [ ${#line} [2] 5 ]; then
    count=$((count + 1))
  fi
done < myfile.txt
echo $count
Drag options to blanks, or click blank then click option'
AIFS=
B>
C-gt
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '-gt' in test brackets
Not setting IFS= causing trimmed lines
5fill in blank
hard

Fill all three blanks to create a dictionary of word lengths for words longer than 3 characters.

Bash Scripting
declare -A lengths
for word in apple banana cat dog elephant; do
  if [ ${#word} [1] 3 ]; then
    lengths[[2]]=[3]
  fi
done
for k in "${!lengths[@]}"; do
  echo "$k: ${lengths[$k]}"
done
Drag options to blanks, or click blank then click option'
A-gt
Bword
C${#word}
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of '-gt' for numeric comparison
Using wrong keys or values in the associative array