【问题标题】:How to read a file in shell script如何在 shell 脚本中读取文件
【发布时间】:2016-07-25 08:29:51
【问题描述】:

我是 shell 脚本的新手。我正在尝试编写脚本。

我有一个日志文件,它每分钟保存一次数据。脚本需要检测该日志文件中的关键字(如果关键字存在)。

我尝试如下:

read jeeva/sample/logs.txt
grep keyword

我知道我的剧本很白痴。请帮我解决这个问题。

【问题讨论】:

  • 通常,grep keyword filename 是在文件中搜索的公认模式。然后因为您每分钟都在这样做,您可以尝试tail -f file | grep keyword,但这是一个脆弱的解决方案,仅适用于命令行使用。寻找旨在解决此问题的实用程序,也许是watcher(有很多,要涵盖现实生活中出现的所有极端情况并非易事)。在此处搜索 [bash] watch 以获取一些想法。祝你好运。
  • @shellter - 我不太确定tail -f(或至少tail -F)是否如此脆弱。我不久前提供了a solution,得到了一些很好的回应,这是基于我多年来一直在运行而没有出现问题的东西。
  • @ghoti 。是的,我应该说“可能很脆弱”。我一定会检查你的答案! Tnx!

标签: linux bash shell grep readfile


【解决方案1】:

这会将文件读入变量

some_var=$(cat jeeva/sample/logs.txt)

但你不需要这样做。你只想检查“关键字”这个词,所以你可以

grep keyword jeeva/sample/logs.txt

如果在脚本中找到,则 $? 将等于 0,否则将等于 1

所以你可以这样做:

grep keyword jeeva/sample/logs.txt
if ! [[ $? ]] 
then 
    echo found 
else
    echo "not found"
fi

【讨论】:

  • 在这里使用$? 有点反模式。你可以做if grep keyword jeeva/sample/logs.txt; then
【解决方案2】:

我猜你只需要监控一些标记的日志消息。 怎么样:

tail -fn 1000 youFile.log | grep yourTag

Tail 在这种情况下似乎更好,因为您不需要重新运行它。

如果你需要脚本试试这个:

#!/bin/bash

while IFS='' read -r line || [[ -n "$line" ]]; do
    if [[ $line == *"$2"* ]]; then
        echo "Do sth here.";
        echo "Like - I've found: $line";
    fi
done < "$1"

$1 是一个文件 $2 是你的标签

➜  generated ./script.sh ~/apps/apache-tomcat-7.0.67/RUNNING.txt UNIX
Do sth here.
Like - I've found:     access to bind under UNIX.

【讨论】:

    【解决方案3】:

    也许你想这样写

    $ if grep -q keyword jeeva/sample/logs.txt; 
      then echo "found"; 
      else echo "not found"; 
      fi
    

    -q 选项是在找到关键字时禁止输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多