bash sed 是否有仅用于检查文件中字符串是否存在的选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16154911/
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
Does sed have an option just for checking existence of string in file?
提问by user2150250
Does sed have an option similar to grep -q, where it returns a 1 or 0 depending on if it actually finds a string match or not?
sed 是否有类似于 的选项grep -q,根据它是否实际找到字符串匹配,它返回 1 或 0?
The reason I ask is in some cases I use sedin particular ways, like finding the first match after a given line number, or setting a capture group and acquiring a string that way, so I wanted to see if sedhad anything built in that would check if anything is returned because I want to throw an error back to the user and exit my bash script if a match isn't found
我问的原因是在某些情况下我使用sed特定的方式,比如在给定的行号之后找到第一个匹配项,或者设置一个捕获组并以这种方式获取一个字符串,所以我想看看是否sed有任何内置的东西可以检查如果返回任何内容,因为我想向用户抛出错误并在未找到匹配项时退出我的 bash 脚本
采纳答案by user2150250
You can set the exit code using the qcommand in sed.
您可以使用 中的q命令设置退出代码sed。
q [exit-code]
Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension.
q [退出代码]
立即退出 sed 脚本而不处理任何更多输入,除非自动打印未禁用,否则将打印当前模式空间。退出代码参数是 GNU 扩展。
See also this answer for a clue.
另请参阅此答案以获取线索。
EDIT:
编辑:
As @cbuckley kindly linked to, you can find directions here.
正如@cbuckley 友情链接的那样,您可以在这里找到方向。
回答by Atlas Wegman
You are much better off using grep -qfor this, but if you ABSOLUTELY want to use sedthen here is how you could replicate the functionality...
你最好使用grep -q它,但如果你绝对想使用,sed那么这里是你如何复制功能......
cat myFile | sed -n "/myString/p" | wc -l
This will pipe out the number of occurences of "myString" in a file. From here you could do a simple test to see if the number is greater then 0, if so return 1, if not return 0. Here is a script demoing how to accomplish this...
这将输出文件中“myString”的出现次数。从这里你可以做一个简单的测试,看看数字是否大于 0,如果是,则返回 1,如果不是,则返回 0。这是一个演示如何完成此操作的脚本...
#!/bin/bash
count=$(cat myFile | sed -n "/\myString/p" | wc -l)
final=0
if [ count -gt 0 ]; then
final=1
else
final=count
fi
echo final
The script above will print out 1 or 0, 1 if the string was found and 0 if it wasn't (note: I haven't checked this, but there's no reason why it wouldn't work).
上面的脚本将打印出 1 或 0,如果找到字符串则打印 1,否则打印 0(注意:我没有检查过这个,但没有理由它不起作用)。
Again, grep -qis the tool for the job and I would recommend using it if at all possible.
同样,grep -q是工作的工具,如果可能的话,我建议使用它。

