我有以下。txt文件:

Marco
Paolo
Antonio

我想逐行读取它,对于每一行,我想为一个变量分配一个.txt行值。假设我的变量是$name,流是:

读取文件的第一行 分配$name = "Marco" 使用$name执行一些任务 从文件中读取第二行 指定$name = "Paolo"


当前回答

#! /bin/bash
cat filename | while read LINE; do
    echo $LINE
done

其他回答

许多人发布了一个过度优化的解决方案。我不认为这是不正确的,但我谦虚地认为,一个不那么优化的解决方案将是可取的,以使每个人都能轻松地理解这是如何工作的。以下是我的建议:

#!/bin/bash
#
# This program reads lines from a file.
#

end_of_file=0
while [[ $end_of_file == 0 ]]; do
  read -r line
  # the last exit status is the 
  # flag of the end of file
  end_of_file=$?
  echo $line
done < "$1"

Use:

filename=$1
IFS=$'\n'
for next in `cat $filename`; do
    echo "$next read from $filename" 
done
exit 0

如果你设置不同的IFS,你会得到奇怪的结果。

使用bash中的IFS(内部字段分隔符)工具,定义用于将行分隔为令牌的字符,默认包括<tab> /<空格> /<newLine>

步骤1:加载文件数据并插入到列表中:

# declaring array list and index iterator
declare -a array=()
i=0

# reading file in row mode, insert each line into array
while IFS= read -r line; do
    array[i]=$line
    let "i++"
    # reading from file path
done < "<yourFullFilePath>"

步骤2:现在迭代并打印输出:

for line in "${array[@]}"
  do
    echo "$line"
  done

访问数组中的一个变量:

echo "${array[0]}"

我鼓励你使用-r标志的read,它代表:

-r  Do not treat a backslash character in any special way. Consider each
    backslash to be part of the input line.

我引用了第一篇文章。

另一件事是将文件名作为参数。

以下是更新后的代码:

#!/usr/bin/bash
filename="$1"
while read -r line; do
    name="$line"
    echo "Name read from file - $name"
done < "$filename"

下面的命令会打印出文件的内容:

cat $Path/FileName.txt

while read line;
do
echo $line     
done