Last active
March 25, 2023 20:57
-
-
Save petergi/b44f8f96e937822a9d7dbf708141560a to your computer and use it in GitHub Desktop.
Simple examples of reading a file in the shell one line at a time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| cat file.txt | while read line || [[ -n $line ]]; | |
| do | |
| printf '%s\n' "$line" # do something with $line here | |
| done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| while IFS= read -r line; do | |
| echo "$line" | |
| done <file |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Option 3: Single line at a time with a file descriptor | |
| filename='file.txt' | |
| exec 4<"$filename" | |
| echo Start | |
| while read -u4 p ; do | |
| echo "$p" | |
| done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Option 2: Single line at a time with Input redirection | |
| filename='file.txt' | |
| echo Start | |
| while read p; do | |
| echo "$p" | |
| done < "$filename" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment