如何 运行 分别对一个文件夹中的所有文件执行 awk,然后将输出合并为一个?
How to run awk on all the files inside a folder separately then combine the output into one?
这是我文件夹中的一种文件,文件夹中还有更多这样的文件:
#ServerName example.com
ServerName www.site1.com site3.com
domain.site4 domain65-something.dom
dasad.sdsd
#ServerName example.f
Databases
#ServerName yeah
我运行这个命令:
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' file
我得到了这个输出:
www.site1.com
site3.com
domain.site4
domain65-something.dom
dasad.sdsd
这正是我想要的。
但我想 运行 对文件夹内的所有文件执行此命令,以便在输出中获得所有虚拟主机。
所以它看起来像这样:
www.site1.com
site3.com
domain.site4
domain65-something.dom
dasad.sdsd
domainform.file2
domain.from.file2
domainfrom.file3
domain.from.file3
请记住,这应该 运行 作为 ansible-playbook 中的 shell 模块。
我试过了:
cat * | xargs awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}'
但它不起作用。我也试过没有 xargs.
只需将命令包装在循环中,使用 ls
获取文件名,并将其输出保存到变量 $file
ls |while read file; do awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' $file; done;
您可以运行循环中对每个文件一个一个地执行命令。
Shell 将在循环结束时自动将输出连接成单个流。
find . -type f \
| while read -r file
do
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' $file
done \
| cat #Here you have entire output for all files. You can pass it to further commands or save to a file.
在您的原始脚本中,只需将 exit
更改为 f=0
并将 file
更改为 *
:
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") f=0}' *
这是我文件夹中的一种文件,文件夹中还有更多这样的文件:
#ServerName example.com
ServerName www.site1.com site3.com
domain.site4 domain65-something.dom
dasad.sdsd
#ServerName example.f
Databases
#ServerName yeah
我运行这个命令:
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' file
我得到了这个输出:
www.site1.com
site3.com
domain.site4
domain65-something.dom
dasad.sdsd
这正是我想要的。
但我想 运行 对文件夹内的所有文件执行此命令,以便在输出中获得所有虚拟主机。
所以它看起来像这样:
www.site1.com
site3.com
domain.site4
domain65-something.dom
dasad.sdsd
domainform.file2
domain.from.file2
domainfrom.file3
domain.from.file3
请记住,这应该 运行 作为 ansible-playbook 中的 shell 模块。
我试过了:
cat * | xargs awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}'
但它不起作用。我也试过没有 xargs.
只需将命令包装在循环中,使用 ls
获取文件名,并将其输出保存到变量 $file
ls |while read file; do awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' $file; done;
您可以运行循环中对每个文件一个一个地执行命令。 Shell 将在循环结束时自动将输出连接成单个流。
find . -type f \
| while read -r file
do
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' $file
done \
| cat #Here you have entire output for all files. You can pass it to further commands or save to a file.
在您的原始脚本中,只需将 exit
更改为 f=0
并将 file
更改为 *
:
awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") f=0}' *