简体   繁体   English

如何在Shell脚本中读取文件

[英]How to read a file in shell script

I am new to shell scripting. 我是Shell脚本的新手。 I am trying to a script. 我正在尝试编写脚本。

I have a log file, which saves the data every minute. 我有一个日志文件,每分钟保存一次数据。 The script needs to detect a keyword in that log file, if the keyword is present on it. 如果该脚本上存在关键字,则脚本需要在该日志文件中检测关键字。

I was trying as below: 我正在尝试如下:

read jeeva/sample/logs.txt
grep keyword

I know my script is idiotic. 我知道我的剧本很白痴。 Please help me with this. 请帮我解决一下这个。

This will read a file into a variable 这会将文件读入变量

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

But you don't need to do that. 但是您不需要这样做。 You only want to check for the word "keyword", so you can just 您只需要检查单词“关键字”,就可以

grep keyword jeeva/sample/logs.txt

In a script if that is found then $? 在脚本中是否找到了$? will equal 0 , otherwise it will equal 1 . 将等于0 ,否则将等于1

So you can do: 因此,您可以执行以下操作:

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

perhaps you want to write it this way 也许你想这样写

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

-q option is to suppress the output when the keyword is found. -q选项用于在找到关键字时禁止输出。

I guess you just need to monitor some tagged log messages. 我想您只需要监视一些带标签的日志消息即可。 How about: 怎么样:

tail -fn 1000 youFile.log | grep yourTag

Tail seems to be better in this case because you don't need to rerun it. 在这种情况下,尾巴似乎更好,因为您不需要重新运行它。

If you need script try this one: 如果您需要脚本,请尝试以下一种方法:

#!/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 is a file $2 is your tag $ 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM