bash - 我们如何从 txt 文件中读取数据并在我的 Bash 代码中使用该数据?这不是关于比较字符串
问题描述
代码.sh
该文件包含以下数据
input="/path/data.txt"
while IFS= read -r line
do
read -p 'Enter the name' name
if(("$name"=="$line"))
then
echo "matched"
fi
done < "$input"
数据.txt
该文件包含以下数据
John
David
taker
我有 2 个文件。文件一是code.sh
和二data.txt
。文件中的上述代码code.sh
仅从data.txt
. 我想从data.txt
条件语句不工作访问数据$line
。我们如何对$line
变量应用操作上面的代码我们没有比较我们想要使用从 txt 文件访问的数据的字符串。访问数据后,我们将比较字符串。
解决方案
继续我的评论,您的问题是您已重定向文件描述符,然后在循环内尝试"$input"
继续阅读。那是行不通的。您需要将输入重定向到另一个文件描述符,以便您可以继续阅读,例如stdin
name
stdin
name
stdin
#!/bin/bash
input="/path/data.txt"
while IFS= read -u 3 -r line ## reads on fd3
do
read -p 'Enter the name: ' name ## reads name on stdin (fd0)
if [ "$name" = "$line" ]
then
echo "matched"
fi
done 3< "$input" ## input redirected on fd3
(注意:字符串相等性测试以及阅读提示格式也已修复name
)
示例使用/输出
$ bash test.sh
Enter the name: John
matched
Enter the name: David
matched
Enter the name: taker
matched
如果您还有其他问题,请告诉我。
推荐阅读
- winapi - DeviceIoRequest 获取用于 USB 存储的 STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR 失败
- java - 当为 Junit 测试设置 Id 时为 id 获取 null
- azure-cognitive-search - Azure 认知搜索、Lucene、全词返回缩写结果
- php - 未发现错误,解析错误:语法错误,PHP 中出现意外标识符“connect”,期待“)”
- sql - SQL Server 报告:将数据类型 nvarchar 转换为数字时出错
- eslint - 在 switch case 中没有表达式的 Eslint 规则
- r - 来自 plm 包的 pFtest 问题返回 p-value = NA
- sql-server - 我可以将参数传递给 SQL 代理作业吗?
- snowflake-cloud-data-platform - 雪花存储过程 - 非空中的空
- non-linear-regression - Ransac 用于对具有多个异常值的数据集进行非线性曲线拟合