0

I have a folder containing files of the pattern shown below. The plan is to loop through every file name, and match everything between the last / and the . which would match the species name plus underscore in between. But I cannot seem to figure out the right regex. After the match works, I would like to save the file under a new name, where _sort is appended to the original file name.

The files to loop through

/home/directory/escherichia_coli.spart
/home/directory/pseudomonas_aeruginosa.spart
/home/directory/pseudomonas_fluorescens.spart
/home/directory/streptocuccus_agalactiae.spart

My most promising attempt:

for i in /home/directory/*.spart; do 
    $i > $i/${i: /$.*\.}_sort.txt; done

/$ to match the last / of the line .* match everything after the last / \. match the dot

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

2

These are glob patterns, not regular expressions. See perhaps What are the differences between glob-style patterns and regular expressions?

Your current code is attempting to run $i as a command and redirect its output to another file. I'm guessing you were looking to copy the file instead.

for i in /home/directory/*.spart; do 
    cp "$i" "${i%.spart}_sort.txt"
done

For your examples, this would produce

cp /home/directory/escherichia_coli.spart /home/directory/escherichia_coli_sort.txt
cp /home/directory/pseudomonas_aeruginosa.spart /home/directory/pseudomonas_aeruginosa_sort.txt
cp /home/directory/pseudomonas_fluorescens.spart /home/directory/pseudomonas_fluorescens_sort.txt
cp /home/directory/streptocuccus_agalactiae.spart /home/directory/streptocuccus_agalactiae_sort.txt

If you really needed to extract just the base name before .spart, the basename command does that, though you can also do it with a second parameter expansion in Bash itself.

for i in /home/directory/*.spart; do 
    base=${i%.spart}
    base=${base##*/}
    echo "$base" should be equivalent to "$(basename "$i" ".spart")"
done

The weird stuff after > in your attempt does not look like Bash syntax at all; are you sure you are not actually using another shell?

tripleee
  • 175,061
  • 34
  • 275
  • 318