2014-04-24 1 views
3

다음은 필자의 작업입니다. 한 줄씩 파일에서 일부 데이터를 읽으십시오. 각 행에 대해 조건을 만족하면 입력을 요구하고 사용자의 입력에 따라 진행합니다. bash에서 파일 * 및 * stdin을 읽는 방법

나는 쉘 스크립트에서 콘텐츠를 한 줄 한 줄을 읽는 방법을 알고

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

그러나, 제가 루프 본체 내부의 사용자 와 상호 작용합니다. 개념적으로, 내가 원하는 것은 다음과 같습니다.

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 

파일을 읽는 다른 방법을 사용해야합니까? stdin을 읽는 다른 방법?

+0

중복 가능성 [판독 루프 내 떠들썩한 파티 표준 입력을 판독 (http://stackoverflow.com/questions/8886683/read-stdin-bash-within-a-read-loop) – BroSlow

답변

9

표준 입력 이외의 파일 설명자에서 파일을 열 수 있습니다.

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 
+0

서지 예 : 나를 위해! 고맙습니다! – monnand

+0

@monnand 좋아요! 마지막에 fd 3을 추가하고 입력/출력에서 ​​열기 명령을 입력으로 변경했습니다. – ooga

+3

또한'exec'의 쌍을 사용하는 대신 루프의 표준 입력을 리디렉션 할 수도 있습니다 :'read -u 3 line; ...; done 3 chepner

관련 문제