Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

linux - How do I tweak my bash script below for searching sub directories

I have a directory with files in the following strcuture:

HomeTransaction1/Date1/transactionfile1.txt
HomeTransaction1/Date1/transactionfile1.xls
HomeTransaction1/Date1/transactionfile2.xls
HomeTransaction1/Date1/transactionfile2.txt
HomeTransaction1/Date1/transactionfile3.txt
HomeTransaction1/Date2/transactionfile1.txt
HomeTransaction1/Date3/transactionfile2.txt
HomeTransaction1/Date3/transactionfile3.txt
HomeTransaction2/Date1/transactionfile1.txt
HomeTransaction2/Date1/transactionfile2.txt
HomeTransaction3/Date1/transactionfile3.txt

I'm trying to get for a specific thing in the transaction files that end in .txt so I'm trying to come up with a bash script to achieve this. Conceptually, this is my thought process.

A - List each folder in the current directory. I this example, it'll be HomeTransaction1, HomeTransaction2 and HomeTransaction3

B - for each folder in B list all the folders(the Date folders)

C - for each folder in step B, run "grep " for files with .txt extension

This is what I have come up with so far:

#!/bin/bash

for FILE in `ls -l`
do
    if test -d $FILE && (startswith "HomeTrasaction") //I want to add a condition to check that the directory name and starts with "HomeTrasaction"
    then
      cd $FILE     // example cd to 'HomeTransaction1' directory
       echo "In HomeTransaction directory $FILE"
       for SUB_FILE in `ls -l` 
        do
         cd $SUB_FILE //example cd to 'Date1'
                echo "In Date directory $FILE"
           for TS_FILES in ($find . -print | grep .txt)
             grep "text-to-search" $SUB_FILE
      
    fi
done

I appreciate any help in finalizing my script. Thank you.

question from:https://stackoverflow.com/questions/65947679/how-do-i-tweak-my-bash-script-below-for-searching-sub-directories

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is actually pretty simple

find ./HomeTrasaction* -iname "*.txt" -exec grep -i "phrase" {} ;

find ./HomeTrasaction* - search each directory that start with this phrase, in the current directory.

-iname "*.txt" - for each file that ends with .txt

-exec grep -i "phrase" {} ; - grep for the word "phrase"

If this is still not clear "man find" :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...