I have a list of files in a directory. Each file has a .txt and a .log extension i.e. file.txt & file.log, file1.txt & file1.log etc. The file with the .log extension may not always exist alongside the file with the .txt extension.
I need to copy the .txt file if there is a corresponding .log file with it. If there is no .log file, then do not do the copy. Once the file has been copied i need to delete it.
I am using ksh on a solaris server.
I have tried the code below to initially assign each file with a .log extension to a variable but i am getting an error:
i=0
for x in /home/dir/*.log
do
arr[$i]=$x
i=`expr $i + 1`
done
echo "${arr[@]}"
error is:
./script.sh arr[0]=/home/dir/file.log: not found
./script.sh arr[1]=/home/dir/file1.log: not found
After this i was going to then cut the .log in the filename and do a search with the .txt extension and then copy it. Can't get the first bit to work though.
for txtfile in /home/dir/*txt
do
filename=${txtfile%.*}
filename=${filename##*/}
if [ -e "${filename}.log" ]
then
cp $txtfile /home/newdir/
rm -f $txtfile
fi
done
Thanks for both them solutions. However, i need them modifying slightly. There will always be corresponding .log file, but the other file may have some other extension that is not known, so it could be .txt, .not, .doc, .ntp etc. Is there any way to account for this in the code?
Don't rm after cp without error checking! Should your cp fail, your file is lost. And, that [^log] might not work. If you've got bash, try (with extglob option set)
for x in *.log; do echo mv ${x%.*}.!(log) /dest/dir; done