read a file line by line
Go through a file's lines in a script, also split into fields, without losing spaces or backslashes.
Steps
-
while IFS= read -r line; do echo "$line"; done < file.txteach line as it is
-
while IFS=, read -r name age; do echo "$name is $age"; done < people.csveach line split at the commas
-
command | while IFS= read -r line; do echo "$line"; doneeach line of a command's output
-
mapfile -t lines < file.txtevery line into an array at once (bash 4)
Notes
for line in $(cat file)splits at every space, not at lines: use while read.- A last line without a newline is skipped by read:
|| [ -n "$line" ]keeps it.
Commands used
readmapfile
Each has a page in lore: lore read opens it.
Related recipes
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.
- check if a string contains a textTest in a script whether a string contains, starts with or matches something.
- count lines of codeHow many lines of code a project has, in total and by language.