Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Replacing a word in the title of a list of files in a folder

    Hi all,

    I have a list of text files in a folder that I incorrectly included 'March22' in the title when I meant to include the word 'May22'. I have about 20 files so don't really want to do this manually. Does anyone have an approach I could try in Stata to loop this? I just want to rename a bunch of files with May rather than March in the title and retain the rest of the title.

    I'm using Stata 15.

    Thanks
    Tim

  • #2
    Assuming by "title" you really mean "file name", have a look at:

    https://www.stata.com/statalist/arch.../msg00295.html

    for a solution using Stata extended macro "dir".

    Comment


    • #3
      Thanks Daniel Feenberg for the reply. I've taken a look at the post you pointed me to but I'm struggling to conceptualise how I strip a string portion from a filename and replace it with another string! I still want to maintain the rest of the filename.

      Comment


      • #4
        Have a look of the "subinstr" macro extended function at page 12 of

        https://www.stata.com/manuals13/pmacro.pdf

        Comment


        • #5
          So I've come up with a solution to find and replace a word in the filename of a bunch of files in the same directory. I would have preferred a tidier find and replace as I need to count the number of characters in and after the target word. This is okay until I realise the naming convention isnt the same for all files!

          Code:
          cd "J:\Data"
          local files: dir . files "*txt"
          foreach f of local files {
          local fnew = substr("`f'",1,7)
          local fnew2 = substr("`f'",16,52)
          local fnew3 = "May22_"
          *di "`fnew'"
          *di "`fnew2'"
          *di "`fnew3'"
          local newname = "`fnew'" + "`fnew3'" + "`fnew2'"
          di "`newname'"
          shell ren "`f'" "`newname'"
          }

          Comment

          Working...
          X