Bash 在读取文件的循环中读取 [英] Bash read inside a loop reading a file

查看:21
本文介绍了Bash 在读取文件的循环中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a script that pulls data from a csv file, manipulates the data, and then asks the user if the changes are correct. The problem is you can't seem to execute a read command inside a while loop that is reading a file. A test script is included below, note a in file will need to be created granted it isn't really used. This is just an excerpt from a larger script I am working on. I'm recoding it to use arrays which seems to work, but would like to know if there is any way around this? I've been reading through several bash guides, and the man pages for read and haven't found a answer. Thanks in advance.

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

推荐答案

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

You can fiddle with the file handles so that you still have access to the old standard input. For example, this file qq.sh will read itself and print each line using your read loop, and also ask you a question after each line:

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<&0 将标准输入(文件句柄 0)保存到文件句柄 3 中,然后使用 read -u code> 从文件句柄中读取的变体 3. 一个简单的脚本:

It does this by first saving standard input (file handle 0) into file handle 3 with the 3<&0, then using the read -u <filehandle> variant to read from file handle 3. A simple transcript:

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> _

这篇关于Bash 在读取文件的循环中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆