User Tools

Site Tools


bash:files:read_a_file:basic_read

This is an old revision of the document!


BASH - Files - Read a file - Basic read

while read -r line; do
  printf '%s\n' "$line"
done < "$file"

NOTE: This reads each line of the file into the line variable.

  • line: is a variable name, chosen by you.
  • -r: Prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters).
    • Without this option, any unescaped backslashes in the input will be discarded.
    • You should almost always use the -r option with read.
  • < “$file”: The file to read.

Prevent removal of leading and trailing white-space characters

while IFS= read -r line; do
  printf '%s\n' "$line"
done < "$file"

NOTE: Very similar to the basic read, but adding usage of IFS.

The IFS (internal field separator) is often set to support reads.

  • IFS= : By default, read modifies each line read, by removing all leading and trailing white-space characters (spaces and tabs, if present in IFS, which is the default).
    • To prevent this, the IFS variable is cleared.
  • line: is a variable name, chosen by you.
  • -r: Prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters).
    • Without this option, any unescaped backslashes in the input will be discarded.
    • You should almost always use the -r option with read.
  • < “$file”: The file to read.
bash/files/read_a_file/basic_read.1611667306.txt.gz · Last modified: 2021/01/26 13:21 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki