逐行读取文件并在 bash 中为每个文件执行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15396190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:50:47  来源:igfitidea点击:

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

bashshell

提问by Marc S.

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.

我需要一个 bash 循环来读取每一行,然后在每次读取一行时执行一个命令,使用该行的输入作为命令的一部分。

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.

我只是不确定在 bash 中执行此操作的正确语法。如果有人可以提供帮助,那就太好了。我需要使用从测试文件中获取的行作为参数来调用另一个函数。当文本文件中没有更多行时,循环应该停止。

Psuedo code:

伪代码:

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

回答by beny23

How about:

怎么样:

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

回答by Fredrik Pihl

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

作为替代方案,使用文件描述符(在本例中为 #4):

file='testfile.txt'
exec 4<$file

while read -r -u4 t ; do
    echo "$t"
done

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

不要用cat!在循环cat中几乎总是错误的,即

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

and people might start to throw an UUoCAat you.

人们可能会开始向你扔UUoCA

回答by user12349296

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.

从 cat 方法更改后,尝试使用此方法自动执行域列表的 nikto 扫描。仍然只是阅读第一行并忽略其他所有内容。