Read file line by line and perform action for each in bash

前端 未结 3 1863
-上瘾入骨i
-上瘾入骨i 2020-12-18 15:09

I have a text file, it contains a single word on each line.

I need a loop in bash to read each line, then perform a command each time it reads a line, using the inpu

3条回答
  •  离开以前
    2020-12-18 16:10

    As an alternative, using a file descriptor (#4 in this case):

    file='testfile.txt'
    exec 4<$file
    
    while read -r -u4 t ; do
        echo "$t"
    done
    

    Don't use cat! In a loop cat is almost always wrong, i.e.

    cat testfile.txt | while read -r line
    do
       # do something with "$line" here
    done
    

    and people might start to throw an UUoCA at you.

提交回复
热议问题