Skip to content

Instantly share code, notes, and snippets.

@ivbor7
Created March 31, 2020 17:46
Show Gist options
  • Save ivbor7/7442fd34f3ec58e3a3a509a09c6417d1 to your computer and use it in GitHub Desktop.
Save ivbor7/7442fd34f3ec58e3a3a509a09c6417d1 to your computer and use it in GitHub Desktop.
Read file line by line in BASH
#read a file from the command line without using the cat command
```sh
$ while IFS= read -r line; do echo $line; done < file.txt
```
#bash script and read any file line by line
```sh
#!/bin/bash
n=1
while IFS= read -r line; do
# reading each line
echo "Line No. $n : $line"
n=$((n+1))
done < /root/file.txt
```
** take a filename as an argument and read the file line by line. **
```sh
#!/bin/bash
while IFS= read -r line; do
echo "$line is the country name"
done < $1
```
**Process Substitution allows the input or output of a command to appear as a file.**
```sh
#!/bin/bash
while IFS= read -r line
do
echo "Welcome to $line"
done < <(cat /root/file.txt )
```
**Here String allows you to pass multiple lines of input to a command**
```sh
#!/bin/bash
while IFS= read -r line
do
echo "$line"
done <<< $(cat /root/file.txt )
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment