0

我对 Linux 很陌生,不懂编程。但是通过阅读一些我可以理解的东西,我可以提问。

我正在做类似下面的事情,

在一个文件中找到几个单词并在另一个文件中采取相应的行动。

find in log.txt
if "not found" 1 > notify.txt
if "reset by peer" 2 > notify.txt
if "Permission denied" 3 > notify.txt
if "Fetching" 0 > notify.txt
exit

喜欢

if [it found] "not found" [text in the log.txt then it will write] 1 > notify.txt
if [it found] "reset by peer" [text in the log.txt then it will write] 2 > notify.txt
if [it found] "Permission denied" [text in the log.txt then it will write] 3 > notify.txt
if [it found] "Fetching" [text in the log.txt then it will write] 0 > notify.txt

请帮我写剧本。

我想在 notify.txt 中写 0 或 1 或 2 或 3。现在脚本将决定写什么。脚本将通过读取 log.txt 文件来决定。

谢谢

4

1 回答 1

1

您的问题有一些含糊不清,但我相信这就是您要寻找的:

#!/bin/bash

# Put the source file / output file in variables
# so they are easier to change
src_file=log.txt
outfile=notify.txt

# Look for the patterns in the source file with "grep":
not_found=$(grep "not found" $src_file)
reset_by_peer=$(grep "reset by peer" $src_file)
perm_denied=$(grep "Permission denied" $src_file)
fetching=$(grep "Fetching" $src_file)

# If the output file already exists, remove it
if [[ -f $outfile ]]; then
    rm -f $outfile
fi

# Create a blank output file
touch $outfile

# If any of the patterns are found, print a number accordingly:
if [[ -n $not_found ]]; then
    echo "1" >> $outfile
fi 

if [[ -n $reset_by_peer ]]; then
    echo "2" >> $outfile
fi 

if [[ -n $perm_denied ]]; then
    echo "3" >> $outfile
fi 

if [[ -n $fetching ]]; then
    echo "0" >> $outfile
fi 

由于您使用多个if块而不是一个if-else if-...-else块来构建您的问题,我假设源文件中可以存在多种模式,如果是这样,您希望在输出文件中显示多个数字。(尽管即使 src 文件中也只能存在一种模式,这仍然有效)

于 2012-11-03T13:09:52.020 回答