In this shell scripting, file contents can be displayed line by line using while loop and word by word using for loop.
Two Operations
- Shell script read file line by line (using while loop)
- Shell script read file word by word (using for loop)
1. Reading File Contents Line by Line via While Loop
- Here file contents can be read using a while loop with read command.
- With help of the read command, the while loop will be used to read the file contents line by line.
- Here input file will be taken at the end of the while loop using input redirection operator <.
- The input redirection operator < will take inputs from file or some other objects instead of keyboard input.
General Syntax of While Loop
while
do
# code
done
File Syntax of While Loop
while read user-defined name
do
# code
done < filename
Where,
read command will read the line of text at a time
< file name represents the input will be taken from file using input redirection operator named <
Example – Displaying File Contents Line By Line
SOURCE CODE (t1.sh)
echo “——————————————-“
echo -e “\t File Contents Line By Line”
echo “——————————————-“
echo “Enter the file name: “
read fn
echo “——————————————-“
# read the file
while read line
do
# print line by line text at a time
echo “$line”
done < $fn
OUTPUT
2. Reading File Contents Word by Word via While Loop
- Here file contents can be read using a for loop with command substitution
- Unlike while loop, it will get input from file using command substitution (assigning command output to a variable)
- By default, for loop will read the contents word by word from the file or other collections
General Syntax of for Loop
for loop-variable in list-of-values
do
# code
done
Where,
loop-variable is an user defined name
in is a reserved word
List-of-values are a set of values which can be integer or char or strings or files, etc. Here each value should be separated by space.
Example 1 – for loop with numeric values
for i in 12 44 55 66
do
echo $i
done
Example 2 – for loop with character values
for i in a f b h k
do
echo $i
done
Example 3 – for loop with string values
for i in “hello” “world” “good” “morning”
do
echo $i
done
File Syntax of For Loop
for loop-variable in $(command)
do
# echo message
done
Where,
loop-variable is an user defined name
in is a reserved word
$(command) is a command substitution, here you need to provide your target input file with help of cat command.
Example: $(cat f1.txt)
Example – Displaying File Contents Word By Word
SOURCE CODE (t2.sh)
echo “——————————————-“
echo -e “\t File Contents Word by Word”
echo “——————————————-“
echo “Enter the file name: “
read fn
echo “——————————————-“
# assign file contents to variable via command substitution
ft=$(cat $fn)
# display the file contents word by word
for i in $ft
do
echo “$i”
done
RESULT
RELATED POSTS
1. Strings in Bash Script
2. Array in Bash Script
3. File Test Operators in Bash Script
4. Switch Case in Bash Script
5. Command Line Arguments
MORE USEFUL TUTORIALS