1

I would to to rename part of a file name, because the structure is hardcoded in getfiles.

I have metabolomics mzML files containing ltQCs, sQCs and samples, but the name of the files have different lenghts (6,6,7).I am trying to run XCMS, but it only picks up ltQCs and sQCs, because the structure is hardcoded to 6. How do I change the structure of the filename see example below:

2020-02-02_B1W1_RP_NEG_P7_A20_001.mzML (structure of 7) to 2020-02-02_B1W1_RP_NEG_P7A20_001.mzML (structure of 6)

I have higlighted the part that I would like to change. If this is impossible, maybe renaming the ltQCs and sQCs may be easier by adding a letter or number, so I get a structure of 7 and then change the structure in getfiles to 7.

Hope somebody can help, thank you:)

Best

  • Hi user12932819. Welcome to StackOverflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). That way you can help others to help you! – dario Feb 20 '20 at 14:19
  • maybe this can help https://stackoverflow.com/a/10759083/12158757 – ThomasIsCoding Feb 20 '20 at 14:22
  • Thank you for you comment, I have tried look into the abovementioned. – user12932819 Feb 20 '20 at 14:35

1 Answers1

0

You can change the file names with a regular expression using gsub which removes the penultimate underline

my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
my_filename <- "2020-02-02_B1W1_RP_NEG_P7_A20_001.mzML"
gsub(my_regex, "\\2", my_filename)
#> [1] "2020-02-02_B1W1_RP_NEG_P7A20_001.mzML"

So you could do something like

rename_mzMLs <- function(directory)
{
  filenames <- list.files(directory, pattern = ".mzML")
  my_regex <- "(_)([[:alnum:]]{3}_[[:alnum:]]{3}[.]mzML)"
  new_filenames <- gsub(my_regex, "\\2", filenames)
  file.rename(filenames, new_filenames)
}

And run it by doing

rename_mzMLs("C:/path/to/mzML/files/")

Obviously, I can't test this since I don't have any mzML files, so ensure you back up your files before running this function!

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Thank you very much! I will try it out - maybe first just on txt files to check. But I have backup of all files, thank you for mentioning that:) – user12932819 Feb 20 '20 at 14:37
  • @user12932819 OK, but remember it will only work on files with a `.mzML` extension, so remember to change you text file names to have that extension. – Allan Cameron Feb 20 '20 at 14:39