我需要在一个循环中的文件中找到一个扩展名为.gz的文件,并从中提取一些数据并打印出来。
我有像d091,d092,.....这样的文件夹,d150,在这些文件夹下有扩展名为.gz的不同文件。我需要从这些。gz文件中打印一些数据。如我所指定的文件中数据的位置。
这是我尝试使用的代码,但它没有工作。如何在for循环中指定路径?
shopt -s nullglob
shopt -s failglob
for k in {091..099}; do
for file in $(ls *.gz)
do
echo ${file:0:4} | tee -a receiver_ids
echo ${file:16:17} | tee -a doy
echo ${file:0:100} | tee -a data_record
done
done
我不确定您的echo | tee
部分正确性,但对于其余部分,您可以尝试如下:
shopt -s nullglob
for dir in d[0-9][0-9][0-9]; do
printf "processing %sn" "$dir"
if [[ -d "$dir" ]]; then
cd "$dir" # enter the directory
for file in *.gz; do # never use ls to get a files list
printf "found [%s] file.n" "$file"
done
cd .. # come back to parent dir
fi
done
如果您不需要分隔目录,可以将其缩短为单个循环:
for file in d[0-9][0-9][0-9]/*.gz; do
fn="${file##*/}"
dir="${file%%/*}"
printf "found [%s] file in [%s] dirn" "$fn" "$dir"
done
我想你可以使用find?
for file in $(find . -name "*.gz"); do
file=$(basename ${file})
echo ${file:0:4} | tee -a receiver_ids
echo ${file:16:17} | tee -a doy
echo ${file:0:100} | tee -a data_record
done