[英]Read a file line by line assigning the value to a variable [duplicate]
我有以下 .txt 文件:
Marco
Paolo
Antonio
我想逐行读取它,并且对于每一行,我想将一个 .txt 行值分配给一个变量。 假设我的变量是$name
,流程是:
$name
= "Marco"$name
做一些任务$name
= "Paolo"以下内容逐行读取作为参数传递的文件:
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
这是在循环中从文件中读取行的标准形式。 解释:
IFS=
(或IFS=''
)防止前导/尾随空格被修剪。-r
防止反斜杠转义被解释。或者你可以把它放在一个 bash 文件帮助脚本中,示例内容:
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
如果将上述内容保存到文件名为readfile
的脚本中,则可以按如下方式运行:
chmod +x readfile
./readfile filename.txt
如果文件不是标准的 POSIX 文本文件(= 不以换行符终止),则可以修改循环以处理尾随部分行:
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
这里, || [[ -n $line ]]
|| [[ -n $line ]]
防止最后一行不以\\n
结尾(因为read
在遇到 EOF 时返回非零退出代码)。
如果循环内的命令也从标准输入读取,则read
使用的文件描述符可能会被其他东西(避免标准文件描述符),例如:
while IFS= read -r -u3 line; do
echo "Text read from file: $line"
done 3< "$1"
(非 Bash shell 可能不知道read -u3
;改用read <&3
。)
我鼓励您使用-r
标志进行read
,它代表:
-r Do not treat a backslash character in any special way. Consider each
backslash to be part of the input line.
我引用了man 1 read
。
另一件事是将文件名作为参数。
这是更新的代码:
#!/usr/bin/bash
filename="$1"
while read -r line; do
name="$line"
echo "Name read from file - $name"
done < "$filename"
使用以下 Bash 模板应该允许您一次从文件中读取一个值并对其进行处理。
while read name; do
# Do what you want to $name
done < filename
#! /bin/bash
cat filename | while read LINE; do
echo $LINE
done
采用:
filename=$1
IFS=$'\n'
for next in `cat $filename`; do
echo "$next read from $filename"
done
exit 0
如果您以不同的方式设置IFS
您将得到奇怪的结果。
许多人发布了一个过度优化的解决方案。 我不认为这是不正确的,但我谦虚地认为,需要一个不太优化的解决方案,让每个人都能轻松理解这是如何工作的。 这是我的建议:
#!/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"
如果您需要同时处理输入文件和用户输入(或来自 stdin 的任何其他内容),请使用以下解决方案:
#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
read -p "> $line (Press Enter to continue)"
done
在这里,我们打开作为脚本参数传递的文件的文件描述符 3 并告诉read
使用这个描述符作为输入( -u 3
)。 因此,我们将默认输入描述符 (0) 附加到终端或其他输入源,以便能够读取用户输入。
正确的错误处理:
#!/bin/bash
set -Ee
trap "echo error" EXIT
test -e ${FILENAME} || exit
while read -r line
do
echo ${line}
done < ${FILENAME}
在bash中使用IFS(内部字段分隔符)工具,定义用于将行分隔成标记的字符,默认包括< tab > /< space > /< 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]}"
以下将只打印出文件的内容:
cat $Path/FileName.txt
while read line;
do
echo $line
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.