文件处理和制作目录在bash中匹配
我有这些文件:File_1.2.txt
,File_1.5.txt
,File_2.3.txt
和File_4.7.txt
。文件处理和制作目录在bash中匹配
我想为它们制作目录并将它们排序到目录中,如下所示。
Dir_001 -> File_1.2.txt File_1.5.txt
Dir_002 -> File_1.2.txt File_2.3.txt
Dir_003 -> File_2.3.txt
Dir_004 -> File_4.7.txt
Dir_005 -> File_1.5.txt
Dir_007 -> File_4.7.txt
因此,一个目录由文件和包含目录的匹配数中的所有文件中使用的每个号码的分类成它。
#!/bin/bash
# If there are no files match File_*.*.txt
# replace File_*.*.txt by empty string
shopt -s nullglob
for i in File_*.*.txt; do
echo "processing file $i"
IFS="_." read foo num1 num2 foo <<< "$i"
printf -v dir1 "Dir_%03d" "$num1"
printf -v dir2 "Dir_%03d" "$num2"
mkdir -pv "$dir1" "$dir2"
cp -v "$i" "$dir1"
cp -v "$i" "$dir2"
done
你应该至少自己尝试过。仅仅复制其他人的代码并不是学习的好方法。
有几种方法可以做到这一点,这里是我的,你的在哪里?
#!/bin/bash
function make_dir
{
#name="Dir00$1"
# Cribbed from the answer given by @Cyrus
printf -v name "Dir_%03d" "$1"
echo "$name"
if [[ ! -d $name ]]
then
mkdir "$name"
fi
}
# I don't need an array here, but I have no idea where these filenames come from
filenames=(File_1.2.txt File_1.5.txt File_2.3.txt File_4.7.txt)
for fname in ${filenames[@]}
do
for seq in {1..999} # No idea what the upper limit should be
do
#if [[ $fname == *$seq* ]]
# Edit: to handle multi-character sequences
if [[ $fname == *[_.]$seq.* ]]
then
dir=$(make_dir $seq)
cp "$fname" "$dir"
fi
done
done
其他人会在这无疑提高。
对函数和序列进行编辑。
这太棒了!我不知道从哪里开始,并且在过去的几个小时里一直在尝试一些东西,但是没有解决。我唯一的问题是,如何在名称=“Dir00 $ 1”中使用类似printf或sprintf的东西,因此一旦我有10个或更多的目录,它就是Dir010而不是Dir0010。 –
@ChemistnotaProgrammer:看看赛勒斯给出的答案,那应该给你一个线索。我犹豫使用他的方法,因为那会是抄袭。你应该增加'{1..7}'中的序列 - 你没有在你的问题中提到数字> 7, – cdarke
@ChemistnotaProgrammer:用'printf -v name'替换'name =“Dir00 $ 1”''Dir_%0.3d “”$ 1“'。 – Cyrus
@cdarke:谢谢。我已经更新了我的答案。 – Cyrus
您能否给我一个IFS =“_”的简要说明。阅读foo num1 num2 foo
该行使用'_'和'.'作为字段分隔符,并且分割字符串(例如)来自$ i的'File_1.2.txt'分为四部分。无用的'File'到$ foo,'1'到$ num1,'2'到$ num2和无用的'txt'再次覆盖$ foo以避免一个新的变量。 – Cyrus