Reputation: 25
I have two folders each containing 351 text files and i want to copy the corresponding text from one folder to corresponding file in another folder? when i am using cat command i am getting an empty file as a result? what could be the problem
my code is :
#!/bin/bash
DIR1=$(ls 2/)
DIR2=$(ls 3/)
for each $i in $DIR1; do
for each $j in $DIR2; do
if [[ $i == $j ]];then
sudo cat $i $j >> $j
fi
done
done
2/ and 3/ are the folders containing the data...
Upvotes: 0
Views: 401
Reputation: 9855
DIR1
and DIR2
contain the file names in directories 2
and 3
respectively.
Apart from possible problems with spaces or special characters in file names, you would have to use 2/$i
and 3/$j
. $i
and $j
alone would reference files with the same names in the current directory (parent of 2
and 3
).
It's better not to parse the output of ls
.
You don't need two nested loops.
#!/bin/bash
DIR1=2
DIR2=3
for source in $DIR1/*
do
dest="$DIR2/$(basename $source)"
if [ -f "$dest" ]
then
sudo cat "$source" >> "$dest"
fi
done
see also https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29
Depending on your needs it may be better to run the whole script with sudo
instead of running sudo
for every file. The version above will only execute cat "$source"
as root. When running the whole script as root this includes also >> "$dest"
.
Upvotes: 2