使用 grep 和 awk 的 BASH FOR 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17277370/
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 05:46:10  来源:igfitidea点击:

BASH FOR loop using grep and awk

bashfor-loopawkgrep

提问by cvjones360

I'm trying to get this script to cata file and grepeach line for 877and for each line found, print the first column which is an IP and store it in hosts. It get stuck on awkevery time. I run sh -x some.shto see where it is hung up. Should I print to a file instead of a list? Why does it get stuck on awk?

我正在尝试将此脚本放入cat一个文件中,并且找到的grep每一行的877每一行,打印作为 IP 的第一列并将其存储在主机中。awk每次都会卡住。我跑去sh -x some.sh看看它挂在哪里。我应该打印到文件而不是列表吗?为什么会卡住awk

hosts=()

FILENAME=/home/somethin/.hosts.conf

ips=`cat $FILENAME | grep -v '877'`

for line in $ips; do
     hosts=$(`awk '{print }'`)
done

echo $hosts

回答by anubhava

It can all be done using awk:

这一切都可以使用 awk 来完成:

hosts=( $(awk '/877/{print }' $FILENAME) )

echo "${hosts[@]}"

回答by Lorenz Lo Sauer

To answer this thread based on the original code, and a corrected version/code-review:

要根据原始代码和更正的版本/代码回答此线程:

#ideally use variable names that do not exist as a command
hosts=()

FILENAME="/home/somethin/.hosts.conf"

ips=`cat $FILENAME | grep '322'`

for line in $ips; do
     hosts+=("`echo $line | awk '{print }'`")
     #alternative for shells not supporting the += operator:
     #hosts=("${hosts[@]}" "`echo $line | awk '{print }'`")
done

echo ${hosts[@]}

There are several issues to point out, that give you the impression your script is "stuck on awk"

有几个问题需要指出,让您觉得您的脚本“卡在 awk 上

  • You are assigning host anew each time hosts=$(`awk '{print $1}'`)
  • Intentionally or not, you are selecting the inverse i.e. non-matcheswith the grep flag -v.
  • You are performing a nested command substitution in dollar and backtick notation, with input that doesn't contain commands: $(awk '{print $1}').
  • awk is not given any input
  • echo variablenamewill only print the first element of a bash array
  • 您每次都重新分配主机 hosts=$(`awk '{print $1}'`)
  • 无论有意与否,您都在选择反向,即与 grep 标志不匹配-v
  • 您正在以美元和反引号符号执行嵌套命令替换,输入不包含命令:$(awk '{print $1}' )
  • awk 没有任何输入
  • echo variablename只会打印 bash 数组的第一个元素

Note: much can be performed with awkand sed, but both are rather intended as shortcuts to more verbose, but also better structured bash/shell skripts which are easier to extend later on. So there is a tradeoff, and there is nothing wrong in the way you started out with....

注意:awk和可以执行很多操作sed,但两者都旨在作为更详细的快捷方式,但也是结构更好的 bash/shell 脚本,以后更容易扩展。所以有一个权衡,你开始的方式没有错......

回答by Davit Samvelyan

Try echo $line | awk '{print $1}'

尝试 echo $line | awk '{print $1}'