Announcement

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

  • Jefferson Abraham
    started a topic Using copy with local macros

    Using copy with local macros

    Hi,

    I am trying to copy files from one several thousand folders to a single folder based on a string present in the files names. The code I'm using is below:

    foreach folder in `branchlist' {
    cd "$path"
    cd "`folder'"
    global branch_code `folder'
    local datelist: dir . dirs *, respectcase
    foreach folder in `datelist' {
    cd "$path"
    cd "$branch_code"
    cd "`folder'
    global date_code `folder'
    local filelist: dir . files *, respectcase
    foreach ele in `filelist' {
    local newname = "$branch_code" + "_" + "$date_code" + "_" + "`ele'"
    shell rename "`ele'" "`newname'"
    if strpos("`newname'","LoansBalanceFile-lond2390.txt")>0 {
    copy "`newname'" `" D:\Bank_Loans\Loan data\loan_balance"`newname'" "'
    }
    }
    }
    }

    I am having trouble with the copy command. I understand it has something to do with the quotes and the macro referencing. But I'm struggling to figure it out. Any help would be much appreciated.

    Jefferson

  • Jefferson Abraham
    replied
    Thank you Nick. It worked.
    I'll also follow the suggestions you have mentioned.

    Leave a comment:


  • Nick Cox
    replied
    You're nesting quotation marks in the target of copy. No need for that at all, and it is unlikely to make sense to Windows.

    There seems to be a lot of unnecessary code here.

    Does this match what you want to do?

    Details:

    1. The name
    folder is used twice over for different things. Not obviously a bug, but a source of lack of clarity.

    2. No obvious need to introduce globals here.

    3. Forward slashes are fine under WIndows in Stata and avoid some nasty problems (documented).

    4. Indenting consistently is a good idea for readers. as is using CODE delimiters. See FAQ Advice #12 as requested.


    Code:
    foreach branch in `branchlist' {
        cd "$path/`branch"
    
        local datelist: dir . dirs *, respectcase
    
        foreach date in `datelist' {
            cd "`date'"
            local filelist: dir . files *, respectcase
    
            foreach ele in `filelist' {
                local newname "`branch'_`date'_`ele'"
                shell rename "`ele'" "`newname'"
                if strpos("`newname'","LoansBalanceFile-lond2390.txt") {
                    copy "`newname'" "D:\Bank_Loans\Loan data\loan_balance`newname'"
                }
            }
        }
    }
    Last edited by Nick Cox; 22 Apr 2017, 12:35.

    Leave a comment:

Working...
X