读取文件中的值,循环直到value = $ foo? [英] Read file for value, loop until value = $foo?

查看:61
本文介绍了读取文件中的值,循环直到value = $ foo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个shell脚本,该脚本对$foo进行摸索,然后计算出现的次数,然后运行命令.每次运行该命令时,该文件中都会少一个$ foo实例.不确定如何继续读取该文件并减少我设置的变量中的值.

I'm writing a shell script that greps for $foo then counts the number of occurrences then runs a command. Each time that command is run, there is one less instance of $foo in that file. Uncertain on how to continuously read that file and reduce the value in the variable I set.

$count= `grep -o $foo /some/file |wc -w`

until [ $count -eq 0 ] 
do
  some_command_that_deletes_foo_in_file
done

但是我意识到$count在运行时设置了一次,并且没有更新.我想要的是$count在脚本遍历/some/file时被更新为/some/file中的当前计数,直到有0个我要查找的短语实例.不确定最佳方法是什么.

However I realize that $count is set once at runtime and is not updated. What I want is $count to be updated to the current count in /some/file while the script is looping through /some/file until there is 0 instances of the phrase I'm grepping for. Uncertain to what the best approach is.

推荐答案

除非您没有向我们展示依赖于$count的其他代码,否则您实际上不需要计算事件的发生.您只需要知道字符串是否出现在文件中即可.为此,您可以编写:

Unless you have additional code that you haven't showed us that depends on $count, you don't actually need to count occurrences; you just need to know whether the string appears in the file. For that, you can write:

while grep -q -- "$foo" /some/file ; do
  some_command_that_deletes_foo_in_file
done

(使用grep会在找到值时返回成功,而在找不到时返回失败,并使用-q标志来禁止其控制台输出).

(using the fact that grep returns success when it finds the value, and failure when it does not, and using the -q flag to suppress its console output).

这篇关于读取文件中的值,循环直到value = $ foo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆