#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r var
do
echo "$var"
done < "$input"
案例
#!/bin/bashfile="/home/vivek/data.txt"while IFS=read-rlinedo# display $line or do somthing with $lineprintf'%s\n'"$line"done<"$file"
如果要按照列来读取
#!/bin/bashfile="/etc/passwd"while IFS=:read-rf1f2f3f4f5f6f7do# display fields using f1, f2,..,f7printf'Username: %s, Shell: %s, Home Dir: %s\n'"$f1""$f7""$f6"done<"$file"
读取文件行到数组
declare-a myarrayleti=0while IFS=$'\n'read-rline_data; do# Parse “${line_data}” to produce content # that will be stored in the array.# (Assume content is stored in a variable # named 'array_element'.)# ... myarray[i]="${array_element}"# Populate array. ((++i))done< pathname_of_file_to_read
最高效的(也是最简单的)方法是将文件的所以行使用bash内建命令readarray读入到一个数组:
declare-a myarrayreadarraymyarray<file_pathname# Include newline.readarray-tmyarray<file_pathname# Exclude newline.
举例:
#!/bin/bashdeclare-a myarray# Load file into array.readarraymyarray<~/.bashrc# Explicitly report array content.leti=0while (( ${#myarray[@]} > i )); doprintf"${myarray[i++]}\n"done