逐行读取文件并将值分配给变量 [英] Read a file line by line assigning the value to a variable
问题描述
我有以下 .txt 文件:
I have the following .txt file:
Marco
Paolo
Antonio
我想逐行读取它,对于每一行,我想将一个 .txt 行值分配给一个变量.假设我的变量是$name
,流程是:
I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is $name
, the flow is:
- 从文件中读取第一行
- 分配
$name
= "Marco" - 用
$name
做一些任务 - 从文件中读取第二行
- 分配
$name
= "Paolo"
- Read first line from file
- Assign
$name
= "Marco" - Do some tasks with
$name
- Read second line from file
- Assign
$name
= "Paolo"
推荐答案
以下内容逐行读取作为参数传递的文件:
The following reads a file passed as an argument line by line:
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
这是用于在循环中从文件中读取行的标准形式.说明:
This is the standard form for reading lines from a file in a loop. Explanation:
IFS=
(或IFS=''
)可防止修剪前导/尾随空格.-r
防止反斜杠转义被解释.
IFS=
(orIFS=''
) prevents leading/trailing whitespace from being trimmed.-r
prevents backslash escapes from being interpreted.
或者你可以把它放在一个bash文件帮助脚本中,示例内容:
Or you can put it in a bash file helper script, example contents:
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
如果以上保存为文件名为readfile
的脚本,可以如下运行:
If the above is saved to a script with filename readfile
, it can be run as follows:
chmod +x readfile
./readfile filename.txt
如果文件不是标准 POSIX 文本文件(= 不以换行符终止),循环可以修改以处理尾随部分行:
If the file isn’t a standard POSIX text file (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
这里,<代码>||[[ -n $line ]] 防止最后一行不以
结尾(因为 read
返回非遇到 EOF 时退出代码为零).
Here, || [[ -n $line ]]
prevents the last line from being ignored if it doesn't end with a
(since read
returns a non-zero exit code when it encounters EOF).
如果循环内的命令也从标准输入读取,则 read
使用的文件描述符可能会被替换为其他内容(避免使用 标准文件描述符),例如:
If the commands inside the loop also read from standard input, the file descriptor used by read
can be chanced to something else (avoid the standard file descriptors), e.g.:
while IFS= read -r -u3 line; do
echo "Text read from file: $line"
done 3< "$1"
(非 Bash shell 可能不知道 read -u3
;改用 read <&3
.)
(Non-Bash shells might not know read -u3
; use read <&3
instead.)
这篇关于逐行读取文件并将值分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!