逐行读取文件的Bash while循环

逐行读取文件的Bash while循环,bash,file-io,while-loop,Bash,File Io,While Loop,有两种逐行读取文件的方法,我想在这里讨论: #!/bin/bash while read line do echo-e "$ line \ n" done <file.txt #/bin/bash 读行时 做 echo-e“$line\n” done第一个循环工作,因为done后的重定向适用于整个循环,因此read从文件中读取,而不是从脚本的标准输入中读取 第二个版本挂起,因为read读取文件描述符0,这是标准输入,而您尚未在其中键入任何内容。e

有两种逐行读取文件的方法,我想在这里讨论:

#!/bin/bash    

while read line    
do    
    echo-e "$ line \ n"    
done <file.txt
#/bin/bash
读行时
做
echo-e“$line\n”

done第一个循环工作,因为
done
后的重定向适用于整个循环,因此
read
从文件中读取,而不是从脚本的标准输入中读取

第二个版本挂起,因为
read
读取文件描述符0,这是标准输入,而您尚未在其中键入任何内容。
exec
行重定向文件描述符3以从文件中读取,但您不是从文件描述符3读取

您可以使用以下方法营救第二个:

exec <file.txt

exec脚本中几乎没有错误

  • $
    和变量名之间的空格。(可能是错误的编辑)
  • echo
    -e
    之间的空格。(可能是错误的编辑)
  • 在打开文件的文件描述符处提及读取。您正在描述符0处读取文件,exec正在描述符3处运行
  • 应该是这样的-

    #!/bin/bash    
    exec 3<file.txt
    
    while read line  
    do
        echo -e "$line \n"
    done <&3
    
    #/bin/bash
    
    exec 3这可能适合您:

    exec 3<file.txt
    
    while read -u3 line
    do
        echo -e "$line \n"
    done
    

    exec 3-u3对我来说很好(只阅读下面一行)

    #/bin/bash
    logs=(*logs.txt)
    [[-e“${logs[0]}”]| |退出0
    
    exec 3Does
    谢谢Jon,我尝试了上面的脚本,它在我的mac上运行。但这是一些有用的信息。我会记得的。我对bash还是很陌生的。刚刚学习了
    awk
    sed
    。但我会开始读一些关于bash基础知识的书。:)已经编辑了答案,在Mac OS/X上运行良好,不要忘记引号:边读边写;不要重复$line;完成
    exec 3<file.txt
    
    while read -u3 line
    do
        echo -e "$line \n"
    done
    
    #!/bin/bash
    
    logs=(*Logs.txt)
    [[ -e "${logs[0]}" ]] || exit 0
    
    exec 3<"${logs[0]}"
    
    while read -u3 line
    do
            if [[ $(echo "$line"| grep -c SCSI_STATUS_CHECK_CONDITION) -eq 1 ]]; then
                    read -u3 line
                    echo "$line"
            fi
    done