脚本:重命名并删除重复的目录

时间:2014-04-22 09:52:30

标签: linux bash shell

我有一个目录结构,其中包含不同的子目录,并带有版本名称 喜欢

/drivers/i2c_v1     
/drivers/i2c_v1_0
/drivers/i2c_v2_1
/drivers/i2c_v3
/drivers/spi_v1
/drivers/spi_v2
/drivers/spi_v2_0
/drivers/spi_v2_1

我需要使用/drivers/i2c_v3重命名/drivers/i2c并删除drivers/i2c_v*/drivers/spi_v2_1 /drivers/spi /drivers/spi_v*并删除{{1}}

最新版本的名称应该重复版本,并且版本保持不变 - 一个人应该这样做 DELETE

任何帮助......

2 个答案:

答案 0 :(得分:1)

prefixes=$(ls /drivers/*_v* | sed 's/_.*//' | uniq)
for p in $prefixes; do
    all=($(ls -vr ${p}_*))  # Sort in reverse version order
    latest=${all[0]}        # So first one is highest version
    mv $latest /drivers/temp    # Rename it so it won't be deleted by wildcard below
    if [[ ${#all[@]} > 1 ]]; then   # Check that there's more than one version
        rm -rf ${p}_*               # Remove the ones other than latest
    fi
    mv /drivers/temp ${p}   # Rename it to the non-versioned name
done

答案 1 :(得分:0)

如果您的文件名使用sort或sort -n

正确排序,请尝试这样的操作
fn=$( ls i2c* | sort -r | head -n1 ); mv -f "$fn" i2c; rm -f i2c_*