首页 > 解决方案 > 我们如何从 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 文件访问的数据的字符串。访问数据后,我们将比较字符串。

标签: bashshell

解决方案


继续我的评论,您的问题是您已重定向文件描述符,然后在循环内尝试"$input"继续阅读。那是行不通的。您需要将输入重定向到另一个文件描述符,以便您可以继续阅读,例如stdinnamestdinnamestdin

#!/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

如果您还有其他问题,请告诉我。


推荐阅读