引言
问题的起因是想要对语料进行数据处理,类似wikipedia的语料基本都是有多层文件结构,类似于text/GS/wiki_01
,编写好了一个针对单一文件的处理程序后,需要对所有文件进行处理,不想用python去编写,那就可以用bash去编写
方法
#!/bin/bash
# loop through all files and subdirectories in the "text" directory
for file in text/*; do
# check if the current file is a directory
if [ -d "$file" ]; then
# if it is a directory, loop through all files in it
for subdirfile in "$file"/*; do
# do something with the file
echo "Processing file: $subdirfile"
done
else
# if it is a file, do something with it
echo "Processing file: $file"
fi
done
讲道理来说,python的glob其实是更加方便的
import glob
glob.glob('text/*/*')
上述就可以获得text文件夹下所有的文件了,不过我们仍然可以尝试使用bash来进行操作,首先是遍历text文件夹下的所有文件,采用[-d "$file"]
的方式判断是否为文件夹,然后再遍历"$file"/*
,对所有子文件夹中的文件进行处理