parsing and rename a file in unix

May 27, 2011 at 13:25:16
Specs: Sun Solaris
Hello,

I have a file extr_x1_x2_x3_x4_201105291211.txt that I'd like to rename to test_201105291211.dat. I don't use unix enough to figure this one out today.

Any ideas?

Thanks


See More: parsing and rename a file in unix

Report •

#1
May 27, 2011 at 15:37:20
If this has to be only once, you can do this at the terminal console by this command:
mv extr_x1_x2_x3_x4_201105291211.txt test_201105291211.dat

If you need to do this periodicly by using a script, let us know.

Click Here on HowTo ask good Question to get best Help
Let us know, if the problem is solved !!!


Report •

#2
May 27, 2011 at 15:41:59
Yes, this will be a daily process with the only change being the datestamp in the filename. The prefix and number of '_' should be the same each day.

Thanks.


Report •

#3
May 27, 2011 at 16:50:35
Maybe something like this:

#!/bin/bash

#set working directory
wd=/tmp/tst/wdir

for x in $(ls $wd/extr_*.txt)
{
    y=$(echo $x | sed 's/extr_x1_x2_x3_x4/test/' | sed 's/\.txt/\.dat/')
    mv $x $y
}

Click Here on HowTo ask good Question to get best Help
Let us know, if the problem is solved !!!


Report •

Related Solutions

#4
May 27, 2011 at 17:31:41
There's more than one way of doing things. This solution assumes the last field is similar to 201105291211.txt no matter how many under scores are in the name:

#!/bin/ksh

cd  <to your directory>
for file in extr_*.txt
do

   # parse the file name
   set -- $(IFS="_"; echo $file)
   # get the last field
   fv=$(eval echo \"\$$#\")

   # parse to the base filename
   set -- $(IFS="."; echo $fv)
   fileb=$1

   # create the new file
   mv "$file"   "test_${fileb}.dat"
done


Report •

#5
May 31, 2011 at 07:09:58
Thanks for the responses! I'll check them out. Both look workable and not something I could easily come up with.

Report •

Ask Question