Removing first 3 characters of file names in linux

萝らか妹 提交于 2019-12-23 03:34:21

问题


I need a sh script to do remove the first 3 characters of file names, for example:

"AB file 1.pdf"
"BC file 2.pdf"
"DB file 3.pdf"
"AD file 4.pdf"
...

to:

"file 1.pdf"
"file 2.pdf"
"file 3.pdf"
"file 4.pdf"
...

I think the script will be like:

#!/bin/sh
for i in *.pdf; do
   newName= ????
   mv $i $newName
done

回答1:


Use the cut command:

newName=$(echo "$i" | cut -c4-)

In bash you can use a Parameter Expansion extension:

newName=${i:3}

Also, don't forget to quote your variables:

mv "$i" "$newName"

Otherwise it will think you're trying to move the files named 'AB,file, and1.pdfto a directory named1.pdf`.

You could also install the rename command if you don't already have it:

rename 's/^...//' *.pdf


来源:https://stackoverflow.com/questions/47316038/removing-first-3-characters-of-file-names-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!