RandomCoder
RandomCoder

Reputation: 99

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.

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.

Any suggestion/help will be appriciated!

Upvotes: 0

Views: 652

Answers (2)

Craig
Craig

Reputation: 776

As mentioned, grep -l can give you a list of files contining you match phrases. Using IFS, you can read that list straight from grep into an array:

#! /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

Upvotes: 0

apatniv
apatniv

Reputation: 1856

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[@]}"

Upvotes: 2

Related Questions