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.

#!/bin/bash
#
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
do
# 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
done

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.

#!/bin/bash
#
DIR=root
FILE=listarmando
DIR_VIDEO=”/media/video”
COPY_DEST=”/media/roarinnas/secondodisco”
y=`cat /$DIR/$FILE|wc -l`
for i in `seq 1 $y`
do
cp -R /$DIR_VIDEO/”`cat /$DIR/$FILE | tail -$i|head -1`” $COPY_DEST
d
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`
do
echo $i
done

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
do
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