Simple script need help

Hi Gurus,

I have a requirement which need copy some files and rename them in same dir.
for example I need to rename all files with ABC at begining of file name.

#! /bin/ksh

filelist=`ls ABC*`
while read file
do
 echo ${file: 0:18}
 cp $file ${file: 0:18}
done <"${filelist}"

i got error when running this
I changed it to

`ls |grep ABC`

I got error as well.

anybody can help this?

thanks in advance.

That is not gonna work. Use a for loop instead:

#!/bin/ksh

for file in ABC*
do
        ...
done
1 Like

It works. thanks.
one more question. if I have two files with different date, for example. ABC20130601, ABC20130605, how could I get latest date file and process it.

thanks in advance

Can you tell us which OS & SHELL you are using?

uname -a 
echo $SHELL

Linux 2.6.32-131.0.15.el6.x86_64 #1 x86_64 x86_64 x86_64 GNU/Linux
/bin/bash

This bash script will help to get the latest file name:

#!/bin/bash

for file in ABC*
do
        current_date="${file#ABC}"
        if [ -z "$latest_file" ]
        then
           latest_file="$file"
        else
           previous_date="${latest_file#ABC}"
           [ $current_date -gt $previous_date ] && latest_file="${file}"
        fi
done

echo "$latest_file"
1 Like

This script works perfectly.
Thank you very very very much!!!

:b: :b: :b:

Hi, give you a simple example, hope to help you.
Assuming there are two files named "file1", "file2" in a specified directory, shown below:

[root@centostest2 20130619]# ls -ls
total 4
0 -rw-r--r-- 1 root root   0 Jun 19 13:59 file1
4 -rw-r--r-- 1 root root  12 Jun 19 11:36 file2

According to your requirement, assuming copy them and change their name respectively to "file1.bak", "file2.bak", the code below works well:

[root@centostest2 20130619]# for x in $(ls file*); do cp ${x} ${x}.bak; echo "****"; done

ps: refer to Yoda's post, it is supposed to be simpler like this:

[root@centostest2 20130619]# for x in file*; do cp ${x} ${x}.bak; echo "****"; done

And the result:

[root@centostest2 20130619]# ls -ls
total 8
0 -rw-r--r-- 1 root root   0 Jun 19 13:59 file1
0 -rw-r--r-- 1 root root   0 Jun 19 14:00 file1.bak
4 -rw-r--r-- 1 root root  12 Jun 19 11:36 file2
4 -rw-r--r-- 1 root root  12 Jun 19 14:00 file2.bak

:slight_smile:

---------- Post updated at 02:40 PM ---------- Previous update was at 02:07 PM ----------

if you're accustomed to use while loop, here it is:

#!/bin/bash
ls -ls file* | gawk '{print $10}' > filelist
while read file
do
        cp ${file} ${file}.bak
        echo "****"
done < filelist
1 Like