Read file line by line and perform action for each

2020-02-11 10:07发布

问题:

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 input from that line as part of the command.

I am just not sure of the proper syntax to do this in bash. If anyone can help, it would be great. I need to use the line from the test file obtained as a paramter to call another function. The loop should stop when there are no more lines in the text file.

Psuedo code:

Read testfile.txt.
For each in testfile.txt
{
some_function linefromtestfile
}

回答1:

How about:

while read line
do
   echo $line
   // or some_function "$line"
done < testfile.txt


回答2:

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.



回答3:

while read line
do
   nikto -Tuning x 1 6 -h $line -Format html -o NiktoSubdomainScans.html
done < testfile.txt

Tried this to automate nikto scan of list of domains after changing from cat approach. Still just read the first line and ignored everything else.



标签: bash shell