tom
tom

Reputation: 5504

How to use sed substitution in bash

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

Answers (2)

perreal
perreal

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

Gilles Quénot
Gilles Quénot

Reputation: 185005

You are taking the wrong way :

  • don't use a for loop to iterate on files to prevent bugs with word spliting. Instead, use find or a while loop
  • don't parse ls output in your scripts, use globs instead

Upvotes: 1

Related Questions