通过bash将文件夹中的某些文件转换为另一个文件

时间:2016-02-16 04:52:53

标签: regex bash file

一般情境

我试图为不同的输入数据运行几次使用2个输入文件的脚本。不修改脚本指出的文件,而是修改相同输入文件的内容,以便脚本不受影响。

特定上下文

我正在运行Asymptote脚本(myScript.asy),该脚本从一对文件中获取数据:data.datsteps.dat并生成图表。

我需要为位于dataFolder内的多个子文件夹中的几对文件生成图表。

这些文件对是可识别的,因为它们以相同的文件名开头,并且只在最后一部分有所不同,例如:40x214_cores.dat40x214_times.dat。它们始终位于同一子文件夹中。

树是这样的:

myScript.asy
data.dat
steps.dat
folderForCharts
dataFolder
  ├ firstSubfolder
  │  ├ AxB_cores.dat
  │  ├ AxB_times.dat
  │  ├ CxD_cores.dat
  │  ├ CxD_times.dat
  │  └ ...
  ├ secondSubfolder
  │  ├ ExF_cores.dat
  │  ├ ExF_times.dat
  │  └ ...
  ├ thirdSubfolder
  │  └ ...

其中A,B,C ......是长度不同的数字(最多7位数)。

问题

面临的挑战是为bash创建一个循环:

  • 分别将AxB_cores.datAxB_times.datcat对的内容分别加入data.datsteps.dat
  • 运行渐近线脚本:asy myScript -o <output filename>,将输出文件存储在folderForCharts中,名称为“originSubfolderName_AxB”,例如:secondSubfolder_54x6789

然后去寻找涵盖所有这些文件的下一对文件。

用于捕获文件对和子文件夹名称的正则表达式让我头晕目眩,所以我有了这个想法,但我不知道如何让它变得真实。
谢谢你给我一些时间,伙计们。

1 个答案:

答案 0 :(得分:1)

以下脚本是否接近您想要的内容?

#!/bin/bash

find . -type f -name '*cores.dat' | while read f
do
    g=${f/cores/times}
    if [ -r "$f" -a -r "$g" ] ; then
      dir=$(dirname "$f")
      axb=$(basename "$f")
      axb=${axb/_cores.dat/}
      echo "process $f and $g with dir=$dir and axb=$axb"
    else
      echo "Cannot find $g" >&2
    fi
done
相关问题