Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

renaming files

17 views
Skip to first unread message

happytoday

unread,
Mar 9, 2012, 9:38:22 AM3/9/12
to
I have created a scipt that rename files like this :

taking a string and convert it to a string delimited by an
underscore .

My issue that I have strings starting with 1.10.1_XYZ and I need to
convert them into 01.10.01_XYZ. Numbers are delimited with a dot . How
can I ccomplish that conversion within my script .


#!/bin/ksh
clear
echo -n "Enter file name :"
read file
file="${file}".c
#if
touch "${file}"
echo ${file}
newfile=`echo "${file}" | sed -e 's/\ /_/g' -e 's/\//_/g'`
echo $newfile
mv "${file}" ${newfile}
vi ${newfile}

Eric Pement

unread,
Mar 9, 2012, 1:42:36 PM3/9/12
to
The sed command (above) suggests that a slash "/" is permitted or
expected as part of the input variable. The slash marks directories
and subdirectories. The 'touch' command is invoked on the unaltered
input. A good script checks to see if a directory exists before trying
to touch a file in that directory.

In the above, the sed script removes slashes from the output name,
with the result that when the 'mv' command executes, a file from a
subdirectory (if it exists) is moved to the current directory.

Since the filename is input manually, I don't think that the slash was
intended as an input character. Here is a version of the script that
should fit this request. It may not work correctly if you are using an
obsolete version of sed.

#!/bin/ksh
clear
echo -n "Enter file name: "
read file
file="${file}".c
touch "${file}"

echo "original filename:" ${file}
newfile=`echo "${file}" | sed -e '
s/ /_/g; # convert spaces to underscore
s/^\([0-9]\.\)/0\1/; # change ^2. to ^02., etc
:loop
s/\.\([0-9][._]\)/.0\1/; # chg .3. to .03., .4_ to .04_, etc
t loop
'`
echo " altered filename:" ${newfile}

[[ "${file}" != "${newfile}" ]] && mv "${file}" ${newfile}
echo vi ${newfile}

Hope this helps.

John W. Krahn

unread,
Mar 9, 2012, 2:39:41 PM3/9/12
to
$ echo "1.10.1_XYZ" | perl -pe's/(\d+)/sprintf"%02d",$1/ge'
01.10.01_XYZ



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction. -- Albert Einstein
0 new messages