问题
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
will have to be renamed pic3.txt
pic1.txt
to pic4.txt
pic2.txt
to pic5.txt
pic3.txt
to pic6.txt
etc…
So the first argument is always the name of a file the second and the third always a positive digit.
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
But the find command does not seem to work. Do you have other solutions ?
回答1:
A possible solution...
#!/bin/sh
NUMBERS=$(ls $1|sed -e 's/pic//g' -e 's/\.txt//g'|sort -n -r)
for N in $NUMBERS
do
NEW=$(($N + 3))
echo "pic$N.txt -> pic$NEW.txt"
mv "pic$N.txt" "pic$NEW.txt"
done
回答2:
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
来源:https://stackoverflow.com/questions/49968718/change-files-numbers-bash