-3

I am going to rename image files and pdf files in a folder in Linux.

It should be recursively as some files are in sub-sub folder.

Current file name pattern is like:

an-yt-h-in-g-123word-123456-anything.jpg (.png .pdf)

My goal pattern is

123456-anything.jpg (.png .pdf)

In a short, I want to remove everything before -NumberString-, and keep everything afterwards (includes the NumberString).

Can anyone help? Thanks a lot

3 Answers3

1

If all your files are named strictly as you said, you may use the command

echo $s | awk -F'-' '{printf "%s-%s", $5, $6}'

to get the new name, assuming that the original filename is held by s.

The renaming can be done simply with mv like

mv $s $(echo $s | awk -F'-' '{printf "%s-%s", $5, $6}')

where s is the original filename as well.

pjhades
  • 1,948
  • 2
  • 19
  • 34
0

This command will check position of last "number string" and output the sub string from this position to the end. You can change ls command to something else.

ls | awk -F '-' '{ for(i=NF; i>=0; i--) { if (match($i, /^[0-9]+$/)) { print $i; for (j=i+1; j<=NF; j++){ printf "-%s" ,$j }; print "\n" } } }' $1 ORS=""

0

an-yt-h-in-g-123word-123456-anything.jpg

For a flat directory of jpegs:

rename 's/.*-[0-9]+-[A-Za-z]+\./\1-\2/.' *.jpg 

For recursively visiting the current dir:

find . \(-name "*.jpg" -o -name "*.pdf" \) -exec rename 's/.*-[0-9]+-[A-Za-z]+\./\1-\2/.' {} ";"
user unknown
  • 35,537
  • 11
  • 75
  • 121