2
$\begingroup$

Consider some directory testfolder located in the directory with the notebook. It contains the following files .dat:

files = FileNames["*.dat", FileNameJoin[{NotebookDirectory[], "testfolder"}]];

Let us assume that these files are "acceptance_1.dat", "acceptance_no.dat", "spectrum_x.dat", "spectrum_12243.dat", such that files are

{"acceptance_1.dat", "acceptance_no.dat", "spectrum_x.dat", "spectrum_12243.dat"}

Could you please tell me which command may leave only the files beginning with acceptance_?

$\endgroup$

2 Answers 2

3
$\begingroup$
files = FileNames["acceptance_*.dat", FileNameJoin[{NotebookDirectory[], "testfolder"}]];

Or do the filtering afterwards like:

files //= Select[StringStartsQ["acceptance_"]]
$\endgroup$
3
$\begingroup$

Another option is to filter out the names inside Mathematica

names = FileNames["*.dat", FileNameJoin[{NotebookDirectory[], "testfolder"}]];

If say

names = {"acceptance_1.dat", "acceptance_no.dat", "spectrum_x.dat", "spectrum_12243.dat"}

Then do

Flatten@StringCases[names, StartOfString ~~ "acceptance_" ~~ __]

Mathematica graphics

You can also add IgnoreCase -> True for Linux systems.

Flatten@StringCases[names, StartOfString ~~ "acceptance_" ~~ __,  IgnoreCase -> True]
$\endgroup$
1
  • $\begingroup$ I would say: files //= Select[StringStartsQ["acceptance_"]] is much more readable and succinct… $\endgroup$
    – SHuisman
    Commented Feb 21, 2023 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.