0

I have a directory with a lot of .cif files. I want to read through the file names and print the ones ending with .cif to a file.

Here is what I tried:

#!/bin/bash

directory=/MOFS

:>| names_mofs

myfilenames="${directory}/*.cif"
for file in $myfilenames
do
   echo $file >> names_mofs

done

But this code prints /MOFS/*.cif into the names_mofs file. I also need to print the whole name, including the .cif extension.

What should I do?

beliz
  • 402
  • 1
  • 5
  • 25

2 Answers2

1

I don't generally advocate using cd in scripts but here, it's by far the easiest way to get rid of the directory name.

( cd /MOFS; printf '%s\n' *.cif ) >names_mofs

The parentheses create a subshell, so the cd doesn't affect the rest of the script outside the parentheses.

If for some reason you want to keep the loop and avoid the cd, the basename command does what you ask. However, the shell can do pretty much the same thing with a parameter expansion.

for file in "$directory"/*.cif; do
    #basename "$file"  # notice proper quoting
    echo "${file##*/}"
done >names_mofs

In brief, ${variable##pattern} produces the value of variable with any prefix which matches pattern removed.

See also When to wrap quotes around a shell variable?

tripleee
  • 175,061
  • 34
  • 275
  • 318
-1
ls -A "$directory" | grep -E '.*\.cif'

That should do it

Shardj
  • 1,800
  • 2
  • 17
  • 43