简体   繁体   English

Bash 脚本 - 如何在目录中的所有 txt 文件中逐一查找 substring 并为所有积极发现写一条消息

[英]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.

相关问题 如何编写bash脚本,将目录中所有子级别的随机文件一个接一个地传递到可执行文件中? - How do I write a bash script to pass random files from all sublevels of a directory into an executable one by one? 我如何编写一个 bash 脚本来遍历文件夹中的每个目录并将所有 .txt 文件附加到一个文件中? - How do i write a bash script to loop through each directory in a folder and append all .txt files into a single file? 使用bash将目录中的所有文件合并为一个 - Merge all files in a directory into one using bash 针对目录和子目录中的所有txt文件运行脚本-BASH - Run script against all txt files in directory and sub directories - BASH Bash 如何删除除一个目录外的所有多个扩展名的文件 - Bash how to delete all files of multiple extensions excluding one directory 在一级目录中查找所有pdf文件 - find all pdf files in a directory at one level Bash脚本:目录中的所有文件 - Bash Script: All files in directory 一个方便的脚本,用于对目录中的所有文件逐个执行程序 - A handy script to execute a program for all files in a directory one by one bash:for循环检索目录中的所有文件仅返回一个 - bash: for loop to retrieve all files in directory only returns one 根据另一个目录中文件的匹配子字符串重命名一个目录中的所有文件 - rename all files in one directory based on a matching substring from files in another directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM