gpt4 book ai didi

regex - 使用 bash 更正文件编号

转载 作者:行者123 更新时间:2023-11-29 09:25:21 26 4
gpt4 key购买 nike

我在这样的文件夹中有一堆文件名:

test_07_ds.csv
test_08_ds.csv
test_09_ds.csv
test_10_ds.csv
...

我想减少每个文件的数量,这样就变成了:

test_01_ds.csv
test_02_ds.csv
test_03_ds.csv
test_04_ds.csv
...

这是我想出的:

for i in $1/*; do
n=${i//[^0-9]/};
n2=`expr $n - 6`;
if [ $n2 -lt 10 ]; then
n2="0"$n2;
fi
n3=`echo $i | sed -r "s/[0-9]+/$n2/"`
echo $n3;
cp $i "fix/$n3";
done;

有没有更简洁的方法来做到这一点?

最佳答案

这可能有帮助:

shopt -s extglob
for i in test_{07..10}_ds.csv; do
IFS=_ read s m e <<<"$i"; # echo "Start=$s Middle=$m End=$e"
n=${m#+(0)} # Remove leading zeros to
# avoid interpretation as octal number.
n=$((n-6)) # Subtract 6.
n=$(printf '%02d' "$n") # Format `n` with a leading 0.
# comment out the next echo to actually execute the copy.
echo \
cp "$i" "fix/${s}_${n}_${e}";
done;

或者把它全部折叠起来

#!/bin/bash
shopt -s extglob
for i in ${1:-.}/*; do # $1 will default to pwd `.`
IFS=_ read s m e <<<"$i"; # echo "Start=$s Middle=$m End=$e"
n=$(printf '%02d' "$((${m#+(0)}-6))")
cp "$i" "fix/${s}_${n}_${e}";
done;

关于regex - 使用 bash 更正文件编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41282297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com