【问题标题】:How to make search of words in several files via bash?如何通过 bash 在多个文件中搜索单词?
【发布时间】:2017-11-13 23:06:07
【问题描述】:

我有一个脚本:

#!/bin/bash

text="hulk hogan,dolph ziggler"
IFS=","
word=( $text )

line=`ls workdir/*.txt`

for a in "${word[@]}"; do
for m in $line; do
if grep -q "$a" "$m"; then
    echo "$a word is exists"
    grep "$a" "$m"
else
    echo "$a word does not exists"
    exit 1
fi
done
done

当我试图找到hulk hogan,dolph ziggler 时,它有效,但前提是这些词存在于所有文件中。

如果first.txt 中存在hulk hogan 而second.txt 中不存在hulk hogan,它将返回错误。

我的错误在哪里?

请帮忙。

我想在所有文件中搜索这些词。在这种情况下,如果数组中的某些单词在所有文件中都不存在,我想得到一个错误,但仅在这种情况下。

但是如果这个词存在于一个文件中,而另一个词存在于另一个文件中,我想得到一个肯定的结果。

感谢您的关注。

【问题讨论】:

  • 问题是exit 1当你找不到单词时,它会立即退出。所以只需删除exit 1这一行。
  • 你就不能grep 'hulk hogan\|dolph ziggler' workdir/*.txt' 吗?
  • 伙计们,我需要exit 1,因为我不想启动脚本的其他部分,如果我在所有文件中都不存在某些单词。根据grep 'hulk hogan\|dolph ziggler' workdir/*.txt' 不,因为我需要在脚本中执行,我将使用 if-else 语句之类的异常。
  • 具体[[ grep 'hulk hogan\|dolph ziggler' workdir/*.txt ]] && echo "word exists" || echo "word does not exist"
  • 至于带有if/else 和循环的脚本。您当前循环浏览每个文件。如果在第一次搜索后未找到搜索词,则退出。不要退出。也许将 true/false 保存到变量中,然后在循环测试变量以查看是否找到它之后。在你的错误条件下退出在这里没有意义。

标签: bash for-loop if-statement search replace


【解决方案1】:

拆分文本后恢复 IFS 以避免意外结果

splitstr() {
    local ifs=$IFS
    IFS=$1 splitstr=( $2 ) IFS=$ifs
}

splitstr , "$text"
word=("${splitstr[@]}")

不要循环 ls 输出,直接使用 glob

for m in workdir/*.txt; do

继续最内层循环的下一个条目

continue

继续下一个封闭循环的下一个条目

continue 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多