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.
Yoda
June 19, 2013, 12:56pm
2
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
Yoda
June 19, 2013, 1:18pm
4
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
Yoda
June 19, 2013, 1:27pm
6
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
yoda:
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"
This script works perfectly.
Thank you very very very much!!!
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
---------- 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