繁体   English   中英

使用 bash 遍历目录,并为每个文件名一一做一些事情

[英]Loop through directory using bash and do something for each file name one by one

所以我有一个要求,我需要在目录中使用 go 并根据模式循环使用具有特定文件名的文件,并获取文件名的某些部分并将其写入文件。 (我正在制作一个用于审计的配置文件)所以我创建了这样的东西,但这会一次性给我文件名,而不是在循环中一个一个地给我。 同时,它并没有脱离循环。 它不断打印文件名和我拥有的其他回声。

注意:在我的实际代码中,我有一些验证来验证时间和所有内容,但是为了最小化这里的代码,我已经删除了它们。

#!/bin/bash   

#Format HH24MI   
TSTMP=$1   
#Source Directory   
INDIR=$2   

while [ `date +"%R" | awk -F":" '{print $1$2}'` -gt "$TSTMP" ]    
do    
  echo "Started scanning source directory."   
  # Process for Incoming files.   
  # Check if any test incoming file is present.   
  cd "$INDIR"   
  IN_FILE_COUNT=`find . -maxdepth 1 -name mytestfile_\*_daily_outgoing_\* -type f | wc -l`   
  if [ "$IN_FILE_COUNT" -gt 0 ]   
  then    
     echo "$IN_FILE_COUNT file/s found in the source directory."   
     for filename in mytestfile_\*_daily_outgoing_\*;    
        do    
           echo $filename    
           ENV=`grep -P $filename | awk -F"_" '{print $2}'`   
           ID=`grep -P $filename | awk -F"_" '{print $5}'`   
           echo $ENV;   
           echo $ID;   
           printf "$ID,$ENV\n" >> myconfigfile     
        done    
  else    
     echo "No incoming file found in the Source directory."   
  fi    
done  

所以现在这里发生了什么,文件被打印在一行中,而不是我的期望是我会得到一个文件名,我将处理然后将详细信息写入文件。 完成后,第二个文件等等。 但是像这样,它无法获取任何值,我的过程只是将空值写入目标文件。 我在源目录中创建了五个文件并尝试使用 find 和 -exec,但由于我不是专家,因此无法完成。 我尝试根据项目的要求偶尔编写一个脚本。 谁能告诉我我做错了什么? 我在 Stackoverflow、askubuntu 等网站上搜索了 20 多页,但没有运气。

我在源目录中的文件:

mytestfile_dev_daily_outgoing_1
mytestfile_test_daily_outgoing_2
mytestfile_dev_daily_outgoing_3
mytestfile_noenv_daily_outgoing_43

预期的目标文件(myconfigfile):

1,dev
2,test
3,dev
43,noenv

我单独测试了 grep 命令,它也可以工作和打印。 所以主要是,我被困在一次循环一个文件名而不是一次全部循环。

太矫枉过正了。 由于您将find限制为-maxdepth 1 ,因此您可以简单地使用for循环遍历目录中的名称。 在你cd "$INDIR"之后,你真正需要的是:

for name in *; do                ## loop over all names in directory
    [ -d "$name" ] && continue   ## if subdirectory, get next
    tmp=${name#*_}               ## trim from left through 1st '_'
    tmp=${tmp%%_*}               ## trim from right through last '_' (leaving e.g. dev)
    echo "${name##*_},$tmp"      ## trim from left to last '_' leaving no. w/$tmp
done

示例使用/输出

将您的示例文件名放在目录中,只需按上述方式循环将导致:

1,dev
2,test
3,dev
43,noenv

(并且由于您使用简单的内置参数扩展来修剪文件名,因此效率很高)

如果您还有其他问题,请仔细查看并告诉我。 根据您的默认文件名排序顺序,如果您想保留按数字排序,您可以将上面的块括在{... }中,然后将 pipe 和 output 括起来进行sort -n

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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