Shell Script to Read Data From a File
File reading is quite an important task in a Programmer’s life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming world. In Linux, we have shell scripting that can do it with just a few lines.
We need to print the contents of a file after reading through it. Firstly, we will need a file to work with so a user input that gets a filename or path. Next, we need to iterate through the file and display the content character by character. The while loops and certain arguments can be used to do it more efficiently.
To read a file, we need a file in the first place. We will simply read from the user input the path to the file or the file name if the file is in the same directory. We are using the read command to input the file path also we are making use of -p argument to pass in a prompt to the user as a text message giving concise information before the user actually types in anything. After the input has been stored in a preferable variable name we then move towards the actual reading of the file.
To read in from a file, we are going to use while loop that reads in from a stream of characters of the file. We used to read and then a variable that stores the current character. We output the character using echo. But the argument we have passed in to read i.e. n1 will allow us to read the file character by character *Note that if you don’t include the argument -n1 you will read the file line by line.* We will continue to loop through unless we are at the EOF or End of File as depicted in the done statement, We can also say the file stream has ended at EOF. If you want to go by more characters we can increment the -n to any desirable number.
Shell Script Code Snippet:
Example 1: Script to read file character by character.
#!/bin/bash read -p "Enter file name : " filename while read -n1 character do echo $character done < $filename
Example 2: Read line by line:
#!/bin/bash read -p "Enter file name : " filename while read line do echo $line done < $filename
Please Login to comment...