![]() Reading files is a very common requirement in Linux and can be used in many bigger scripts. In this article, we have learnt different ways to read file line by line shell script. If you want to omit backslash escape, then you need to use -r option with read command in your while loop, as shown below. Please note, if your file contains backslash then the above code will treat it as escape character. Now you can run your shell script file as $. In the above code, $1 stores the first command line argument. If you want to pass the filepath via command line argument, replace the second line of your script as filename=$1 ![]() Run the shell script using the following command. Make the shell script executable $ sudo chmod +x read_file.sh We also use $n variable to keep count of line number. Then we run a while loop through the file, storing each line in $line variable. In the above code, we store file path in $filename variable. Once you have created an empty shell script with the above command, add the following lines to it. Here is a simple shell script to read the file and display its contents line by line. $ while read line do echo $line done < /home/ubuntu/data.txt Please note, if you don’t use the full path below, it will look for the file in your present working directory. Each line is temporarily stored in $line variable. ![]() In the above code, the while loop goes through the file. If you don’t want to write a shell script or even use cat command to view your file contents, you can use a while loop in terminal prompt to simply go through the file line by line and display its contents. Here are the different ways to read the above file line by line. How to Read File Line by Line in Linux Shell Script Suppose you have a file /home/ubuntu/data.txt with the following information Today In this article, we will look at different use cases for reading file in shell script. Often you may need to read file line by line in Linux shell script.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |