Nov 292009

I don’t consider myself a script guru, but sometimes I like to create small pieces of bash code to ease operations on my linux box… and I guess it’s good idea to note here some of the recent solutions I’ve found for later remembering.

I’ll try to comment them, so that readers will be able to readapt them to their needs.

Need: I have a list of files in subdirectories under main one and I want to copy only some of them to new location. I have the list of files I need in a text file.

DIR=root # Location where the list I want to extract is located
FILE=wantedlist # with the name of the file
DIR_VIDEO=”/media/bigdisk” # Master repository containing iles in subdirectories
COPY_DEST=”/media/externalHDD/backup” # where I want to put my files
y=`cat /$DIR/$FILE|wc -l` # counting how many files I want to copy
for i in `seq 1 $y` # starting the cycle
# I’ll copy file mentioned in every line in the text list in new location
cp -R /$DIR_VIDEO/”`cat /$DIR/$FILE | tail -$i|head -1`” $COPY_DEST

Please note the usage of head and tail to go line by line in reverse order ;), while the cycle allows me to repeat this for each line in the text list.

y=`cat /$DIR/$FILE|wc -l`
for i in `seq 1 $y`
cp -R /$DIR_VIDEO/”`cat /$DIR/$FILE | tail -$i|head -1`” $COPY_DEST
Feb 032009

You might need to do something with a list of files contained in a fileā€¦ and maybe these file names include spaces, therefore using a standard

for i in `cat filename`
echo $i

does not work since it will consider every word as a single variable.

This second script does the job:

IFS=\$    ==> this sets the line separator as EOL
while read i    ==> this read variables separated by EOL and stores value in $i
echo $i    ==> this echoes the value of $i. Replace echo command with whatever you want to do with filenames
done < file-containing-the-list    ==> this ends the while do cycle and takes input from file where filenames are stored