开发者

Find folder path based on each character of a word and use grep on selected file

I want to run the code below and use grep to search for "LARGE_NAME" inside a file that is in a path that needs yet to be determined. Important:

  • Both file and folder names are just 1 distinct letter of the alphabet [a-z];
  • Files have no file extension. Example: "$dir/$letter1/$letter2", $letter2 is the file;
  • I know that I found the path if there is no more subfolders to be searched.

.

./query.sh LARGE_NAME

The final file could be in:

$dir/$letter1
$dir/$letter1/$letter2
$dir/$letter1/$letter2/$letter3/
.... so on

Where:

$letter1 = L
$letter2 = A
$letter3 = R
.... so on 

I want to optimize my code that works but have too many nested IFs. Below is an example with just 3 letter search:

query.sh file:

#!/opt/homebrew/bin/bash
dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

letter1=$(echo ${1,,}|cut -b1)
if [ -f "$dir/$letter1" ]; then
    grep -ai "^$1&quo开发者_Python百科t; "$dir/$letter1"
else
    letter2=$(echo ${1,,}|cut -b2)
    if [ -f "$dir/$letter1/$letter2" ]; then
        grep -ai "^$1" "$dir/$letter1/$letter2"
    else
        letter3=$(echo ${1,,}|cut -b3)
        if [ -f "$dir/$letter1/$letter2/$letter3" ]; then
            grep -ai "^$1" "$dir/$letter1/$letter2/$letter3"
        fi
    fi
fi

How can I rewrite my code to search for up to 50 sub folders until it finds the last/final one with the file I want to grep?


So build the path cummulatively, one slash and letter at a time.

input=${1,,}
path="$dir"
for ((i = 0; i < ${#input}; ++i)); do
    letter=${input:i:1}
    path="$path/$letter"
    if [[ -f "$path" ]]; then
        grep -ai "^$1" "$path"
    fi
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜