I am new to scripting, so any help on this would be much appreciated.
I am trying to rename a bunch of files, taking the names sequentially from a list read in another file...
# ls oldnames
file_1
file_2
file_3
# cat names
red
yellow
green
I want the files to take on the names red yellow green as they are read line by line from the file "names"
ie
cp oldnames/file_1 newnames/red
cp oldnames/file_2 newnames/yellow
cp oldnames/file_3 newnames/green
etc....
What I have tried (but doesn't work) -
#! /bin/bash
ls . |while read line
do
echo $line
cat names | while read xx
do
cp $line ../newnames/$xx
done
done
This creates new files but only copies the last entry from the ls to each of them
As you can see my scripting skills are not great - any ideas would be much appreciated.
to start with:
invoked from the parent old 'oldnames' direcotry. Assumes 'oldnames' and 'newnames' direcotries are SIBLINGS and the file 'names' resides in the parent of 'oldnames'.
Adjust to fit the actual requirement.
Good luck!
#!/bin/ksh
ls oldnames | while read old
do
while read new
do
cp oldnames/"${old}" newnames/"${new}"
done < names
done
#!/bin/sh
path="/path/oldnames"
newpath="/path/newname"
ls $path | awk -v path=$path -v newpath=$newpath ' pass the variables path and newpath to awk
BEGIN{
# this "BEGIN" block will be executed first before any input record is processed
q="\047" # set variable q to contain the single quote
while( (getline f < "names" ) > 0 ) {
# get the contents of "names" file, using f to store each line as the while loop iterates the file
# then store the value of each line (f) to array "a". "c" is the index of the array
a[++c]=f
}
close("names") # close the file
}
{
# process the results of "ls" command, putting each file listed into array "b", and increment the index
b[++d]=$0 #
}
END{
# the below is done at the very end of processing the inputs.
for ( i=1; i<=c;i++) {
cmd="cp "q path"/"b q" "q newpath"/"aq
print cmd
#system(cmd) #uncomment to execute
}
}
'
I think You would be helped with an array, assuming the number of files in oldnames is equal to the number of names in the list names. In bash it would be something like:
mkdir newnames
cnt=0
newname=($(< names))
for x in oldnames/*; do
cp $x newnames/${newname[$cnt]}
cnt=$(($cnt+1))
done