简体   繁体   English

如何在bash中从文件*和* stdin读取

[英]How to read from file *and* stdin in bash

Here is my task: read some data from file line by line.这是我的任务:逐行从文件中读取一些数据。 For each line, if it satisfies some condition, then ask user to input something and proceed based on the user's input.对于每一行,如果它满足某个条件,则要求用户输入内容并根据用户的输入进行操作。

I know how to read content line-by-line from a shell script:我知道如何从 shell 脚本中逐行读取内容:

while read line; do
   echo $line
done < file.txt

However, what if I want to interact with the user inside the loop body.但是,如果我想要做什么用的循环体的用户进行交互。 Conceptually, here is what I want:从概念上讲,这是我想要的:

while read line; do
    echo "Is this what you want: $line [Y]es/[n]o"
    # Here is the problem:
    # I want to read something from standard input here.
    # However, inside the loop body, the standard input is redirected to file.txt
    read INPUT
    if [[ $INPUT == "Y" ]]; then
       echo $line
    fi
done < file.txt

Should I use another way to read file?我应该使用另一种方式来读取文件吗? or another way to read stdin?或另一种读取标准输入的方式?

You can open the file on a file descriptor other than standard input.您可以在标准输入以外的文件描述符上打开文件。 For example:例如:

while read -u 3 line; do     # read from fd 3
  read -p "Y or N: " INPUT   # read from standard input
  if [[ $INPUT == "Y" ]]; then
    echo $line
  fi
done 3< file.txt             # open file on fd 3 for input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM