[英]Bash script - How to find substring in all txt files in directory one by one and write a message for all positive findings
This is what I'm asked to do.这是我被要求做的。
Browse all text (regular / plain) files in the specified folder (the first parameter of the script) and look for the specified word in them (the second parameter of the script).浏览指定文件夹(脚本的第一个参数)中的所有文本(常规/纯文本)文件,并在其中查找指定的单词(脚本的第二个参数)。 If the file contains the specified word, write the message: "YES, the word $2 is in $file".
如果文件包含指定的单词,则写入消息:“是的,单词 $2 在 $file 中”。 Otherwise write: "NO, there is no word $2 in $file"
否则写:“不,$file 中没有单词 $2”
Here is what i came with so far:到目前为止,这是我带来的:
#!/bin/bash
FILES=$1
for file in $FILES
do
if [ $file == "*$2*" ];then
echo "YES, the word $2 is in $file"
else
echo "NO, there is no word $2 in $file"
fi
done
Using find
使用
find
#!/usr/bin/env bash
pattern=$2
folder=$1
export pattern
find "$folder" -type f -exec sh -c '
for f; do
if grep -q "$pattern" "$f"; then
printf "%s is in %s\n" "$pattern" "$f"
else
printf "%s is not found in %s\n" "$pattern" "$f"
fi
done' _ {} +
Howto use.如何使用。
./myscript folder pattern
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.