在 for 循环中使用 awk 的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3835128/
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
Bash script using awk in for loop
提问by Stan
for i in $LIST
do
CFG=`ssh $i "cat log.txt|awk '{print }'"`
for j in $CFG
do
echo $j
done
done
Say I want to print 2nd field in the log file on a couple remote host. In above script, print $2 doesn't work. How can I fix this? Thanks.
假设我想在几个远程主机上打印日志文件中的第二个字段。在上面的脚本中,print $2 不起作用。我怎样才能解决这个问题?谢谢。
采纳答案by psj
try
尝试
for i in $LIST
do
ssh $i "cat log.txt|awk '{print $2}'"
done
回答by schot
Depending on the number of shell expansions and type of quoting multiple backslash escapes are needed:
根据 shell 扩展的数量和引用的类型,需要多个反斜杠转义:
awk '{ print }' log.txt # none
ssh $server "awk '{ print $2 }' log.txt" # one
CFG=`ssh $server "awk '{ print \ }' log.txt"` # two
CFG=$(ssh $server "awk '{ print $2 }' log.txt") # one (!)
As a trick you can put a space between the dollar sign and the two to prevent all $ expansion. Awk will still glue it together:
作为一个技巧,您可以在美元符号和两者之间放置一个空格以防止所有 $ 扩展。Awk 仍然会将它粘合在一起:
CFG=`ssh $i "cat log.txt|awk '{print $ 2}'"`
回答by zigdon
Make sure you're escaping the $2from the shell - the ssh command you end up sending right now is something like this: ssh listvalue cat log.txt|awk '{print }'
确保您正在$2从 shell 中转义- 您现在最终发送的 ssh 命令是这样的:ssh listvalue cat log.txt|awk '{print }'
回答by gsbabil
for server in $LIST
do
ssh "$server" 'awk "{print }" log.txt'
done
- Carefully watch the location of the
single-quoteand thedouble-quote. - Bash tries to expand variables (
words beginning with $) inside double-quote ("). - Single-quote (
') stops Bash from looking for variables inside. - As
user131527andpsjsuggested, escaping$2with\should also have worked (depending on how your Bash is configured).
- 仔细观察的位置
single-quote和double-quote。 - Bash 尝试
words beginning with $在双引号 (")内扩展变量( )。 - 单引号 (
') 阻止 Bash 在内部查找变量。 - 作为
user131527和psj建议,逃避$2与\也应该有工作(根据您的Bash是如何配置的)。
回答by Turbo
I was able to put awk in a double for loop
我能够将 awk 放入双 for 循环中
for i in 1 2 3 4;do
for j in $\(ls | awk -v I=$i '{print $I}');
echo $j
done;
done
for i in 1 2 3 4;do
for j in $\(ls | awk -v I=$i '{print $I}');
echo $j
done;
done
回答by ghostdog74
Lose the cat. Its useless..
丢了猫。这毫无用处..
for server in $LIST
do
ssh "$server" "awk '{print $2}' log.txt"
don

