Bash - 在文件名中间添加0

时间:2011-03-09 07:59:30

标签: bash shell

我有一堆名为的文件:

mem0.csv
mem1.csv




mem153.csv


它们都在同一个文件夹中。当我在文件夹中执行时,它们按照

的顺序出现

mem0.csv
mem1.csv
mem10.csv
mem100.csv



mem2.csv
mem20.csv


我想创建一个bash脚本来在mem和数字之间推送0。我认为我需要添加0,直到所有文件名长度相同,唯一的问题是我不知道该怎么做。

4 个答案:

答案 0 :(得分:4)

GNU coreutils提供的ls支持version sort

$ ls -v
mem0.csv
mem1.csv
mem2.csv
...
mem10.csv
...

答案 1 :(得分:3)

您可以使用printf工具,只需确保您的系统有它(几乎所有现代系统都有) 要将它们全部重命名:

for i in {1..153}; do
    mv mem$i.csv mem`printf "%03d" $i`.csv
done

编辑: 对于随机数量的文件,代码将变为如下:

dir = "/somedir"
fn = $(ls -l $dir | wc -l)
z = 0;
c = $fn
# Count the number of zero's to use
while [ $c -gt 0 ]; do
    (( $z++ ))
    c = $(( $c / 10 ))
done
# Rename the files
while [ $fn -gt 0 ]; do
    mv ${dir}/mem$fn.csv ${dir}/mem$(printf "%0${z}d" $i).csv
    (( $fn-- ))
done

答案 2 :(得分:1)

我认为ls -v(正如@ephemient所说)做你想要的,但是如果你真的必须用零填充数字,这里是基于提供的文件名模式的快速和肮脏的方式

last=$(ls -v *.csv | tail -n1) # last file has the biggest number
let max=${#last}-7 # minus the number of all the other chars (constant)

# below grep gets only the number part and head ignores the last line
# which we don't need to change 
ls -v mem*.csv | egrep -o '[0-9]+' | head -n -1 | \
while read n; do
    mv -ivf mem$n.csv mem$(printf "%0"$max"d" $n).csv
done

答案 3 :(得分:0)

行。我是这样做的。我知道这不是正确的方法,但通过这种方式,我有可能理解其中的东西

#Cleaning the dest folder
cd "out"
rm *
cd ".."

#setting some variables
MAXLEN=-1

#Searching for the longest file name
for f in mem*.csv; do
   LEN=${#f}
   if [  $MAXLEN -lt $LEN  ]; then
      let MAXLEN=$LEN
   fi
done

for f in mem*.csv; do
   LEN=${#f}
   let LEN+=1
   COUNT="0" 
   until [ $MAXLEN  -lt $LEN  ]; do #Creating 0's string to add
      COUNT=$COUNT"0"
      let LEN+=1
   done
      CLEN=${#COUNT} #The string has one 0 more than it should have. We take that into an account
      let CLEN-=1
      echo $CLEN
      if [  $CLEN != 0  ]; then
         COUNT=${COUNT:0:$CLEN} #The string is to long, remove the last 0
         number=$(echo $f | tr -cd '[[:digit:]]') #Extracting the number from the rest of the file name
         cp $f "out/mem"$COUNT$number".csv" #creating the new file

 else
         cp $f "out/"$f
      fi
done


ls "out/"