File Reading Functionalities

File reading is an interesting task in a programmer’s life. Shell scripting offers some functionalities for reading the file, reversing the contents, counting words, lines, etc.

  • Reading line by line: First, we take input using the read command then run the while loop which runs line after line.

Script:

#!/bin/bash
read -p "Enter file name : " filename
while read line
do 
echo $line
done < $filename

  • Counting characters, words & lines in the file: We take three variables, one for counting characters, words, and lines respectively. We use ‘wc’ command, which stands for word count and counts the number of characters and words as well. For counting lines, we pass ‘grep ‘ which keeps count of the lines that match a pattern. Then we print out each variable.

 Script:

#! /bin/bash

echo Enter the filename
read file
c=`cat $file | wc -c`
w=`cat $file | wc -w`
l=`grep -c "." $file`
echo Number of characters in $file is $c
echo Number of words in $file is $w
echo Number of lines in $file is $l

  • Display file contents in reverse: To print the contents of any file in reverse, we use tac or nl, sort, cut commands. Tac is simply the reverse of a cat and simply prints the file in reverse order.  Whereas nl commands numbers, the file contents sort the numbered file in the reverse order, and the cut command removes the number and prints the file contents.

 Script:

$ nl geeks.txt | sort -nr | cut -f 2-

  • Frequency of a particular word in the file: To count the frequency of each word in a file, we use certain commands. These are xargs which applies print to every line in the output, the sort which sorts, current buffer piped to it, uniq -c displays the counts of each line in the buffer and, lastly awk, prints the 2nd column and then the 1st column based on the problem requirement.

      Script:

cat geeks.txt | xargs printf “%s\n” | sort | uniq -c | sort -nr | awk ‘{print $2,$1}’

Shell Script to Perform Operations on a File

Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file.

For our convenience, we create a  file named ‘geeks.txt’ and another .sh file (or simply run on the command line) to execute different functions or operations on that file. Operations may be reading the contents of the file or testing the file type. These are being discussed below with proper examples:

Similar Reads

File Reading Functionalities

File reading is an interesting task in a programmer’s life. Shell scripting offers some functionalities for reading the file, reversing the contents, counting words, lines, etc....

File Test Operators

-b file: This operator checks if the file is a block special file or not and returns true or false subsequently. It is [-b $file] syntactically....

Contact Us