Bash脚本从文档中读取文件名和类别,并相应地将文件排列到文件夹中

时间:2015-06-03 12:15:48

标签: bash

我正在开发一个包含数百个文件的项目。该项目附带一个文档文件(一种“索引”),其中包含文件名和特定文件名所属的类别。 e.g。

Filename1 > Category1
Filename2 > Category2

现在我想安排所有文件,使“Category”成为“Folder”,其中包含属于该类别的所有文件。即。

Folder1 contains all files belonging to category1
(And name of the Folder1 is "Category1")

手动执行此操作需要大量时间,因为文件名称不合适。

那么如何编写一个可以从文档中读取“文件名”和“类别”的Bash脚本,然后创建一个文件夹(名称为“Category”)并将属于该类别的所有文件复制到该文件夹​​中?

修改

也许我在问题中给出的例子非常简单。实际问题比这复杂一点。 无论如何,我已经研究了几天的bash脚本了,我已经成功地创建了一个可以满足我想要的脚本。

这是脚本:

#!/bin/bash
#script to arrange files of the project "BodyParts3D" into respective folders
#The index file (reference.txt) is arranged in such a way that it contains three columns: Concept_ID, Name and File_ID (in this order)

#Variables I need to begin with (I know there is no need for that but just for my own reference
concept_id=0;
file_id=0;
name=0;
prev_concept_id=0;

#Start a while loop to read the file line by line

while read -r line; do

#Initiate a word_count variable that is reset with every "while" loop
  word_count=0;

#Start a for loop within the while loop to read the line word by word
  for word in $line; do

#Add the words in the line into an array
    array[$word_count]=$word;
    let word_count++;
  done
#Concept_ID is the first word in every line 
concept_id=${array[0]};

#File_ID is the last word in every line
file_id=${array[-1]};

#The remaining part of the line is the Name
  unset array[0];
  unset array[-1];
  name=$(printf " %s" "${array[@]}");
  name=${name:1};

#Unset the array so that in the next "while" loop, the array begins from the start
  unset array;

#If Concept_ID is a new one, then create a separate folder for it and copy the respective file into that folder
  if [ "$concept_id" != "$prev_concept_id" ]; then
    mkdir "$concept_id $name";
    cp "$file_id.obj" "$concept_id $name";
  fi

#If Concept_ID is the same as previous line, then only copy the file into the already existing folder
  if [ "$concept_id" == "$prev_concept_id" ]; then
    cp "$file_id.obj" "$concept_id $name";
    echo "cp";
  fi

#set the current Concept_ID as prev_concept_id so that the new one can be compared with it in the next loop
  prev_concept_id=$concept_id;
done <reference.txt

这完全符合我希望它做的工作。但我能以更好的方式做到吗?

1 个答案:

答案 0 :(得分:0)

bash中的循环可能是最简单的解决方案:

#!/bin/bash
while read -r f_name _ dir_name _; do
   echo mkdir -p -- "$dir_name"
   echo cp -- "$f_name" "$dir_name/"
done < category_file

验证输出后删除echo命令