简体   繁体   English

将包含两个特定字符串的文件列出到bash中的数组中

[英]list files containing two specific strings into an array in bash

Inside a directory(without any subdirectories) I have several text files. 在目录内(没有任何子目录),我有几个文本文件。

I want to create a array containing the list of files which contains specific two Strings say Started uploading and UPLOAD COMPLETE . 我想创建一个包含文件列表的数组,其中包含特定的两个字符串,例如Started uploadingUPLOAD COMPLETE

for i /directory_path/*.txt; do
  #perform operations on 1
done

This is considering all the text files present in the directory. 这是在考虑目录中存在的所有文本文件。 Here, in i I want only the files which contains the above said strings. 在这里, i想只有它包含的文件上面说的字符串。

Any suggestion/help will be appriciated! 任何建议/帮助都将适用!

If you continue with your code, then do can do this 如果继续执行代码,则可以执行此操作

declare -a files; 
for i in directory_path/*.txt; do
   if grep -q 'Started Uploading' "$i" && grep -q 'UPLOAD COMPLETE' "$i"; then
       files+=("$i")
   fi 
done

echo "matching files: ${files[@]}"

As mentioned, grep -l can give you a list of files contining you match phrases. 如前所述,grep -l可以为您提供一系列匹配短语的文件。 Using IFS, you can read that list straight from grep into an array: 使用IFS,您可以将列表从grep直接读取到数组中:

#! /usr/bin/env bssh

OLD_IFS=$IFS
IFS=$'\n'

declare -a array=( $(grep -l 'Started uploading\|UPLOAD COMPLETE' "dir"/*) )

IFS=$OLD_IFS

echo "count: ${#array[@]}"
printf "    %s\n" "${array[@]}"

You do have to save/restore IFS 您必须保存/恢复IFS

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

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