我有以下.txt文件:
Marco
Paolo
Antonio
Run Code Online (Sandbox Code Playgroud)
我想逐行读取它,并且对于每行我想为变量分配.txt行值.假设我的变量是$name
,流程是:
$name
="Marco"$name
$name
="保罗"cpp*_*der 1268
以下(另存为IFS=
)读取作为参数逐行传递的文件:
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
Run Code Online (Sandbox Code Playgroud)
说明:
IFS=''
(或-r
)防止修剪前导/尾随空格.readfile
防止反斜杠转义被解释.|| [[ -n $line ]]
如果最后一行不以a结尾\n
(因为read
在遇到EOF时返回非零退出代码),则阻止忽略最后一行.运行脚本如下:
#!/bin/bash
while IFS= read -r line; do
echo "Text read from file: $line"
done < "$1"
Run Code Online (Sandbox Code Playgroud)
....
Grz*_*cki 302
我鼓励你使用以下-r
标志read
代表:
-r Do not treat a backslash character in any special way. Consider each
backslash to be part of the input line.
Run Code Online (Sandbox Code Playgroud)
我引用了man 1 read
.
另一件事是将文件名作为参数.
这是更新的代码:
#!/usr/bin/bash
filename="$1"
while read -r line; do
name="$line"
echo "Name read from file - $name"
done < "$filename"
Run Code Online (Sandbox Code Playgroud)
小智 126
使用以下Bash模板应该允许您一次从文件中读取一个值并进行处理.
while read name; do
# Do what you want to $name
done < filename
Run Code Online (Sandbox Code Playgroud)
小智 71
#! /bin/bash
cat filename | while read LINE; do
echo $LINE
done
Run Code Online (Sandbox Code Playgroud)
Rau*_*una 20
许多人发布了一个过度优化的解决方案.我不认为这是不正确的,但我谦卑地认为,一个不太优化的解决方案将是可取的,以便每个人都能轻松理解这是如何工作的.这是我的建议:
#!/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"
Run Code Online (Sandbox Code Playgroud)
小智 19
使用:
filename=$1
IFS=$'\n'
for next in `cat $filename`; do
echo "$next read from $filename"
done
exit 0
Run Code Online (Sandbox Code Playgroud)
如果你设置IFS
不同,你会得到奇怪的结果.
如果您需要处理输入文件和用户输入(或stdin中的任何其他内容),请使用以下解决方案:
#!/bin/bash
exec 3<"$1"
while IFS='' read -r -u 3 line || [[ -n "$line" ]]; do
read -p "> $line (Press Enter to continue)"
done
Run Code Online (Sandbox Code Playgroud)
在这里,我们打开文件描述符3作为脚本参数传递的文件,并告诉read
使用此描述符作为input(-u 3
).因此,我们将默认输入描述符(0)附加到终端或另一个输入源,能够读取用户输入.
为了正确处理错误:
#!/bin/bash
set -Ee
trap "echo error" EXIT
test -e ${FILENAME} || exit
while read -r line
do
echo ${line}
done < ${FILENAME}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1548423 次 |
最近记录: |