修改脚本以从条件中删除else(Modify script to remove else from condition)

编程入门 行业动态 更新时间:2024-10-25 02:22:55
修改脚本以从条件中删除else(Modify script to remove else from condition)

我试图使用while循环从一个文件中找到一些关键字,如果它们存在与否则检查另一个文件。 如果不是,则应将其写入另一个文件中。 以下是我的代码

while read -r line; do if grep -q -e "$line" $file_name; then echo "character found" else echo "$line" >> notfound.txt fi done < result.txt`

我觉得整个if条件可以通过排除else部分以及回声“找到的字符”来简化,因为有很多字符。 请帮忙删除它。 我试过-v但不幸的是没有用。

也可以使用while循环从可能的第3行和结束2行开始

提前致谢!

I am trying to find a few key words from one file using while loop and checking in another if they are present or not. If not they should be written in another file. Below is my code

while read -r line; do if grep -q -e "$line" $file_name; then echo "character found" else echo "$line" >> notfound.txt fi done < result.txt`

I feel that the whole if condition can be simplified by excluding the else part and also the echo "character found" as there are a lot of characters. Please help in removing this. I tried -v but unfortunately didn't work.

Also is it possible for using while loop starting from maybe the 3rd line and end 2 lines before

Thanks in advance!

最满意答案

当然可以在一行中完成,通过在执行时检查命令的返回码,参见bash,exit-codes

#!/bin/bash while read -r line do # On successful search 'grep' returns code '0', negating it for the # unsuccessful case to return a 'true' condition ! grep -q -e "$line" "$file_name" && echo "$line" >> notfound.txt done <result.txt

Of course it can be done in a single line, by checking the return-code of the command as it is executed, see bash, exit-codes

#!/bin/bash while read -r line do # On successful search 'grep' returns code '0', negating it for the # unsuccessful case to return a 'true' condition ! grep -q -e "$line" "$file_name" && echo "$line" >> notfound.txt done <result.txt

更多推荐

本文发布于:2023-08-05 22:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1441119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   条件   Modify   condition   remove

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!