Reputation: 175
Lets say I have file, named, blabla.txt which looks like this :
blabla.php <usb>blabla /bla/bla
blabla.js <usb>blabla /bla/bla
I want to write script which will check if blabla.php, blabla.js exists, one by one, and if string exist than will copy source file using path to target file using path and replace source instead of target file.
Source path would be:
<usb>blabla
Target path would be:
/bla/bla
so I am first time in contact with bash scripts, and I would appreciate if you try to explain it on beginners level for me, I tried this until now ( also little bit is pseudo code ):
while read line; do
for filename in $line; do
if grep -Fxq "$filename" blabla.txt
cp $filename+1 $filename+2
done
done
I am sure that I made some big mistakes ( like trying to copy string into string but i dont know how to find path of actual file and copy )
Upvotes: 0
Views: 1061
Reputation: 753970
Assuming that the blanks in the file separate the important fields and are never part of a name, then you can do something along the lines of:
while read file source target junk
do
if [ -n "$junk" ]
then echo "Unexpected junk at end of line: $file $source $target $junk"
elif [ -f "$source/$file" ]
then
[ -d "$target" ] || mkdir -p "$target" || exit 1
cp "$source/$file" "$target/$file" || exit 1
else
echo "No such file: $source/$file" >&2
fi
done < blabla.txt
The description of what you want to do isn't all that clear.
This code reads each line of blabla.txt
into 4 variables, splitting on white space. This is a fabulously useful feature of read
. Then the code checks that there are at most 3 fields on the line. If there was extra information, it would be stored in $junk
; the -n
test checks whether $junk
is non-empty and if so, the line is ignored. If the source file exists (and is a file), then the code ensures that the target directory exists (creating it if it does not, and exiting if it fails to create it), and then copies the source file to the target directory (exiting if there is a problem). If the source file doesn't exist, the problem is reported.
You can tweak this in multiple ways, depending on what you really want to do. You can decide not to exit but to continue to the next line if there's a problem with directory creation, or the copy fails. However, once on copy fails, it is likely that the rest will too. For example:
if [ -d "$target" ] || mkdir -p "$target"
then cp "$source/$file" "$target/$file"
fi
You can consider using read -r …
; I don't, but I don't mind 'living dangerously' (but the aficionados around here prefer you to use it, so you get told you can use the -r
and you can decide for yourself whether you will).
Upvotes: 1
Reputation: 781068
You should read each column of the file into a different variable that represents its role.
while read -r filename sourcedir destdir
do
if [[ -e "$sourcedir/$filename" ]]
then
cp "$sourcedir/$filename" "$destdir"
fi
done < inputfile
Upvotes: 2