I had list of files in the folder named test_images as below
006103insettedryshampoo-blossom7096.jpg 008299bathmassagesponges-3packa1a4.jpg 008507colgatetripleactiontoothpaste125d.jpg 8729teatreeoilantisepticcream25g1005.jpg
i want to rename all file by removing last four characters from each of them as
006103insettedryshampoo-blossom.jpg 008299bathmassagesponges-3pack.jpg 008507colgatetripleactiontoothpaste.jpg 8729teatreeoilantisepticcream25g.jpg
How can i do it using sed ?
Any suggestion will be appreciated.
Thanks in advance 🙂
Advertisement
Answer
if your file names don’t have spaces, you can: (under your test_images
dir)
ls -1|sed -r 's/(.*)....(.jpg)$/mv & 12/'
to check the generated mv
command. If it is ok, add |sh
to the above command to do the actual renaming.
If your filenames have spaces, you need add quotes:
..../mv "&" "12"/'|sh
This is a quick and dirty solution, since working with ls result is not good practice.
update: add “how to” example:
LsyHP 11:41:40 /tmp/test/img kent$ ll total 0 drwxr-xr-x 2 kent kent 120 Jan 4 11:41 ./ drwxr-xr-x 3 kent kent 160 Jan 4 11:41 ../ -rw-r--r-- 1 kent kent 0 Jan 4 11:41 006103insettedryshampoo-blossom7096.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 008299bathmassagesponges-3packa1a4.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 008507colgatetripleactiontoothpaste125d.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 8729teatreeoilantisepticcream25g1005.jpg LsyHP 11:41:43 /tmp/test/img kent$ ls -1|sed -r 's/(.*)....(.jpg)$/mv & 12/' mv 006103insettedryshampoo-blossom7096.jpg 006103insettedryshampoo-blossom.jpg mv 008299bathmassagesponges-3packa1a4.jpg 008299bathmassagesponges-3pack.jpg mv 008507colgatetripleactiontoothpaste125d.jpg 008507colgatetripleactiontoothpaste.jpg mv 8729teatreeoilantisepticcream25g1005.jpg 8729teatreeoilantisepticcream25g.jpg LsyHP 11:41:52 /tmp/test/img kent$ ls -1|sed -r 's/(.*)....(.jpg)$/mv & 12/'|sh LsyHP 11:41:57 /tmp/test/img kent$ ll total 0 drwxr-xr-x 2 kent kent 120 Jan 4 11:41 ./ drwxr-xr-x 3 kent kent 160 Jan 4 11:41 ../ -rw-r--r-- 1 kent kent 0 Jan 4 11:41 006103insettedryshampoo-blossom.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 008299bathmassagesponges-3pack.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 008507colgatetripleactiontoothpaste.jpg -rw-r--r-- 1 kent kent 0 Jan 4 11:41 8729teatreeoilantisepticcream25g.jpg