更改文件编号Bash [英] Change file's numbers Bash
问题描述
我需要实现一个脚本(duplq.sh),该脚本将使用命令行参数重命名当前目录中存在的所有文本文件.因此,如果执行命令 duplq.sh pic 0 3
,它将进行以下转换:
I need to implement a script (duplq.sh) that would rename all the text files existing in the current directory using the command line arguments. So if the command duplq.sh pic 0 3
was executed, it would do the following transformation:
pic0.txt
必须重命名为 pic3.txt
pic1.txt
到 pic4.txt
pic2.txt
到 pic5.txt
pic3.txt
到 pic6.txt
等...
因此,第一个参数始终是文件名,第二个参数和第三个参数始终是正数.
So the first argument is always the name of a file the second and the third always a positive digit.
我还需要确保执行脚本时,第一次重命名(将pic0.txt更改为pic3.txt)不会删除当前目录中现有的pic3.txt文件.
I also need to make sure that when I execute my script, the first renaming (pic0.txt to pic3.txt), does not erase the existing pic3.txt file in the current directory.
这是我到目前为止所做的:
Here's what i did so far :
#!/bin/bash
name="$1"
i="$2"
j="$3"
for file in $name*
do
echo $file
find /var/log -name 'name[$i]' | sed -e 's/$i/$j/g'
i=$(($i+1))
j=$(($j+1))
done
但是find命令似乎不起作用.您还有其他解决方案吗?
But the find command does not seem to work. Do you have other solutions ?
推荐答案
查找
可能的文件,按编号对名称进行 sort
,使用 sed
删除编号小于 $ 1
的文件,按编号反向 sort
,然后从顶部开始,从最高编号重命名为最低编号:
find
possible files, sort
the names by number, use sed
to remove files with lower numbers than $1
, reverse sort
by number, and start at the top renaming from the highest number down to the lowest:
#!/bin/sh
find . -maxdepth 1 -type f -name "$1"'[0-9]*' |
sort -g | sed -n "/^$1$2."'/,$p' | sort -gr |
while read x ; do
p="${x%%[0-9]*.*}"; s="${x##*[0-9]}" ; i="${x%$s}" i="${i#$p}"
mv "$x" "$p$((i+$3))$s"
done
这篇关于更改文件编号Bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!