【问题标题】:Modify script to remove else from condition修改脚本以从条件中删除 else
【发布时间】:2017-02-20 14:26:25
【问题描述】:

我正在尝试使用 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 部分和 echo "character found" 来简化,因为有很多字符。请帮助删除它。我试过 -v 但不幸的是没有用。

也可以使用 while 循环从第 3 行开始并在 2 行之前结束

提前致谢!

【问题讨论】:

标签: unix grep aix


【解决方案1】:

当然可以在一行中完成,通过在执行时检查命令的返回码,参见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

【讨论】:

    【解决方案2】:

    忘记它;使用 comm(1) 这就是它的好处。示例:

    #!/usr/local/bin/bash
    
    cat >needles <<DONE
    p1
    n1
    p2
    n2
    DONE
    
    cat >haystack <<DONE
    p3
    p2
    p1
    DONE
    
    comm -23 <(sort -u needles) <(sort -u haystack)
    

    【讨论】:

      【解决方案3】:

      假设$filename 是任意文本文件,result.txt 是包含单词列表的文件,每行一个。

      #!/bin/bash
      
      # 1. get the list of words found in the file, store in an array
      mapfile -t found < <(grep -owFf result.txt "$filename" | sort -u)
      
      # 2. get the list of words not found
      grep -vxFf <(printf "%s\n" "${found[@]}") result.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-30
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多