Tuesday, November 27, 2012

Linux Shell script to convert numbers to star's in a file name

Q. One of the blog follower asked this question. Write a LINUX shell script that accepts an arbitrarily long list of file names as arguments and replaces all digits in them with a "*".

This is bit tricky and the solution I got is below script


#!/bin/bash
for i in $(ls | grep '[0-9]')
do
eval mv $i $(echo $i | sed 's/[0-9]/\\\*/g')
done


Some of the issues I faced are
1)In sed I tried to replace numbers with just * which created an issue
2)In sed I tried to replace numbers with \\* which is still not working.

So I tried to use eval to get this solution. I advantage of eval is that it will try to evaluate a shell code on the fly.
ls | grep [0-9] will give you the files which contain a single number in its filename, this output is feed in to for loop and each value is read in to i variable.

sed 's/[0-9]/\\\*/g' Will search for a number in the filename and replace it with \*.
eval command will convert mv $filename $(echo $i | sed 's/[0-9]/\\\*/g') to mv file1name file\*name

Hope this helps.


4 comments:

  1. see here http://ss64.com/bash/for.html
    for command is showing ; semicolon before "do" and "done" are these required ?

    ReplyDelete
  2. there is no -r option here http://ss64.com/bash/sed.html . where we are replacing numbers with star (*) and how ?. and why we are moving (mv) ... I thought its the simple renaming of files ..Right ? and what is s and g in 's/[0-9]/\\\*/g' regex

    ReplyDelete
  3. hi jolly,

    They are not at all required. Semicolon shows that command completes after ;. This semicolon is used to write script in one line as shown in your link. But here I am writing for loop in multiple lines. If you want to convert my script in to single line script:

    for i in $(ls | grep '[0-9]');do eval mv $i $(echo $i | sed -r 's/[0-9]/\\\*/g'); done

    ReplyDelete
  4. In SED man pages you will come to know what is -r indicted(-r indicates regular expression enable). My mistake there is no need for -r option. updated the post as there is no regular expressions.

    To understand the sed code you should know below things.
    https://www.google.com/url?q=http://www.linuxnix.com/2012/04/learn-sed-examples.html
    https://www.google.com/url?q=http://www.linuxnix.com/2011/07/regular-expressions-linux-i.html

    There is no renaming related command, mv is the renaming command.

    ReplyDelete