Reputation: 5504
I'm trying to get the unique file name before the "_"
, and copy only those files. Below is the script, but I must be missing something about the sed
Example of my file name - P2.D2.C00_21, P2.D2.C00_22
#!/bin/bash
echo "Step 1"
names=$(ls ./Folder1 | sed 's//.*_//' | uniq)
echo "Step 2"
for name in `echo $names`
do
echo "Step 3"
files=($(ls -v ./Folder1/${name}.* | xargs -n1 basename))
echo "step 4"
cp -f ./Folder1/${files[${#files[@]} - 1]} ./folder2
echo "step 5"
done
Upvotes: 0
Views: 69
Reputation: 97928
This one finds the part after _
:
sed 's//.*_// # should be 's/_.*//'
but since you are globbing after uniq, I don't see the benefit of sed at all. Also, using ls
is a very bad practice, you should rely in globbing instead.
If you don't mind using Perl:
for (glob("Folder1/*")) {
($a,$b,$c)=/((.*)_(.*))/;
push @{$h{$b}}, $c;
}
for $b(keys %h) {
system("cp '${b}_$h{$b}[-1]' folder2/");
}
Upvotes: 1
Reputation: 185005
You are taking the wrong way :
word spliting
. Instead, use find
or a while loopls
output in your scripts, use globs insteadUpvotes: 1