简体   繁体   中英

Iterate through subdirectories and execute an awk script against certain files

I have a directory named ../words that contains a number of subdirectories(words/blabla,words/blabla), in turn each subdirectory contains two types of files (.*1.txt) and (.*2.txt) . What I need, it is to execute an AWK script against each one of these files.

Could it be something like?

for d in words/*
do
    for f in .*[0-9].txt
    do
    awk -f script.awk ${f}
    done
done

If you want to keep your for statement structure and apply the awk script to each specified file, you can do the following:

for file in $(find words -type f -name ".*[12].txt"); do
    awk -f script.awk "$file"
done

The find command is useful for recursively looking through a directory for any pattern of files.


Edit: If your file names contain things like spaces, the above script may not process them properly, so you can do the following instead:

find words -type f -name ".*[12].txt" -print0 | while read -d $'\0' file
do 
    awk -f script.awk "$file"
done

or using xargs:

find words -type f -name ".*[12].txt" -print0 | xargs -0 awk -f script.awk

This allows you to delimit your file names with null \\0 characters, so variations in name spacing or other special characters will not be a problem. (You can find more information here: Filenames with spaces breaking for loop, and find command , or here: Handling filenames with spaces , or here: loop through filenames returned by find ).

鉴于您到目前为止告诉我们的内容,这应该是您所需要的:

awk -f script.awk ../words/blabla/.*[12].txt

如果您需要跳过中间目录级别,仅查看子目录下的内容,则可以使用最大/最小深度

$ find words -maxdepth 2 -mindepth 2 -type f -name '*[0-9].txt' | xargs awk -f ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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