我是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文件来决定。
由于
答案 0 :(得分: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文件中只存在其中一个模式,这也有效)