如何在bash中操作文件名?

时间:2014-07-18 12:46:12

标签: bash ubuntu scripting

我有一堆我需要重命名的图像,所以我可以使用它们,我想知道如何做到这一点。

他们需要的方式是保留前5,然后在6日我会写1-3的数字。我只知道前5个是静态的;在属于同一“家庭”的照片上,可以用于比较,第6个字符不知道。

示例:

  

12345random.jpg

     

12345randomer.jpg

     

0987654more_random.jpg

     

09876awesome.jpg

     

09876awesomer.jpg

     

09876awesomest.jpg

     

09876soawesomegalaxiesexplode.jpg

会成为。

  

12345.jpg

     

123452.jpg

     

09876.jpg

     

098761.jpg

     

098762.jpg

如果它只处理循环以便3个图片只能重命名并且休息跳过它会很酷。

我找到了一些删除字母的东西,但没有任何用处,因为我在bash脚本方面很差。

这是我的方法,但它有点糟糕,因为我尝试修改我发现的脚本,但想法就在那里

//I could not figure how to remove the chars after 5th not the other way around
for file in .....*; do echo mv $file `echo $file | cut -c6-`; done

done
//problem also is that once the names conflict it produces only 1 file named 12345.jpg 2nd one will not be created
    //do not know how to read file names to array
    name=somefile
    if [[ -e $name.jpg]] ; then
        i=0
        while [[ -e $name-$i.jpg]] ; do
            let i++
        done
        name=$name-$i
    fi
    touch $name.jpg

2 个答案:

答案 0 :(得分:3)

你可以:

new_file=${file%%[^0-9]*.jpg}.jpg

作为一个概念,您可以重命名文件:

for file in *.jpg; do
    [[ $file == [0-9]*[^0-9]*.jpg ]] || continue  ## Just a simple check.
    new_file=${file%%[^0-9]*.jpg}.jpg
    [[ -e $new_file ]] || continue  ## Do not overwrite. Delete line if not wanted.
    echo "Renaming $file to $new_file."  ## Optional message.
    mv -- "$file" "$new_file" || echo "Failed to rename $file to $new_file."
done

如果您要处理同时包含目录名称的文件,则需要进行更多更改:

for file in /path/to/other/dirs/*.jpg *.jpg; do
    base=${file##*/}
    [[ $base == [0-9]*[^0-9]*.jpg ]] || continue
    if [[ $file == */* ]]; then
        new_file=${file%/*}/${base%%[^0-9]*.jpg}.jpg
    else
        new_file=${file%%[^0-9]*.jpg}.jpg
    fi
    [[ -e $new_file ]] || continue
    echo "Renaming $file to $new_file."
    mv -- "$file" "$new_file"
done

答案 1 :(得分:1)

您也可以尝试以下代码 但请注意,所有文件都应采用.jpg格式,并将文件夹名称作为参数传递

#!/bin/bash
a=`ls $1`
for b in $a
do
echo $b
if (( i<4 ))
then 
c=`echo $b | cut -c1-5`
let i=i+1
c="$c$i.jpg"
echo $c
else
c=`echo $b | cut -c1-5` 
c="$c.jpg"
break
fi
mv $1$b $1$c
done