【问题标题】:Bash read inside a loop reading a fileBash 在循环中读取文件
【发布时间】:2012-03-27 22:45:12
【问题描述】:

我正在编写一个脚本,该脚本从 csv 文件中提取数据、操作数据,然后询问用户更改是否正确。问题是您似乎无法在读取文件的 while 循环内执行读取命令。下面包含一个测试脚本,注意需要创建一个 in 文件,前提是它并没有真正使用。这只是我正在处理的更大脚本的摘录。我正在重新编码它以使用似乎有效的数组,但想知道是否有任何解决方法?我一直在阅读几个 bash 指南,以及阅读的手册页,但没有找到答案。提前致谢。

#!/bin/bash
#########
file="./in.csv"
OLDIFS=$IFS
IFS=","
#########

while read custdir custuser
do
    echo "Reading within the loop"
    read what
    echo $what
done < $file

IFS=$OLDIFS

【问题讨论】:

  • 您可能会发现 awk 是您尝试做的更好的选择。

标签: bash while-loop


【解决方案1】:

您可以修改文件句柄,以便您仍然可以访问旧的标准输入。例如,这个文件qq.sh 将读取自己并使用您的read 循环打印每一行,并且还在每一行之后问你一个问题:

while read line
do
    echo "    Reading within the loop: [$line]"
    echo -n "    What do you want to say? "
    read -u 3 something
    echo "    You input: [$something]"
done 3<&0 <qq.sh

它首先使用 3&lt;&amp;0 将标准输入(文件句柄 0)保存到文件句柄 3 中,然后使用 read -u &lt;filehandle&gt; 变体从文件句柄 3 中读取。一个简单的脚本:

pax> ./qq.sh
    Reading within the loop: [while read line]
    What do you want to say? a
    You input: [a]
    Reading within the loop: [do]
    What do you want to say? b
    You input: [b]
    Reading within the loop: [echo "Reading within the loop: [$line]"]
    What do you want to say? c
    You input: [c]
    Reading within the loop: [echo -n "What do you want to say? "]
    What do you want to say? d
    You input: [d]
    Reading within the loop: [read -u 3 something]
    What do you want to say? e
    You input: [e]
    Reading within the loop: [echo "You input: [$something]"]
    What do you want to say? f
    You input: [f]
    Reading within the loop: [done 3<&0 <qq.sh]
    What do you want to say? g
    You input: [g]
    Reading within the loop: []
    What do you want to say? h
    You input: [h]
pax> _

【讨论】:

  • 谢谢 我正要问它是如何解决的。这适用于小测试脚本,现在合并到实际脚本中。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 2013-10-12
  • 2021-04-16
  • 2022-01-22
  • 1970-01-01
  • 2014-06-17
相关资源
最近更新 更多