Announcement

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

  • Removing the last characters from a string

    Afternoon,

    I am trying to shorten a file name, so that it omits the last 4 characters. I am using Stata 14.

    The data files have names such as: 200112dvb.dta, 20013ascasde.dta, 20013gbfer.dta

    The code I am using is:

    Code:
    local years 2001 2002
    foreach year of local years{
    cd "dir"
    local files : dir . files "`year'*.dta"
    foreach f of local files {
    disp "`f'"
    local file = substr("`f'", 1, length(`f')-4)
    }
    }
    However, the code I am using returns an error r(198). In particular, it says 200112dvb: operator invalid.

    Any assistance would be much appreciated.
    Last edited by Dann Morgan; 02 Jun 2017, 13:40.

  • #2
    Hi Dann,

    I believe your issue is because you are using the command length instead of the command strlen. Try that and let me know of your results!

    Junie

    Comment


    • #3
      Thanks Junie. Unfortunately I still get the same error message.

      Comment


      • #4
        You need double quotes around the dereferenced local `f' given as an argument to length(), which expects a string.
        Code:
        local file = substr("`f'", 1, length("`f'")-4)

        Comment


        • #5
          You need " " around each mention of the local macro f. Otherwise you're trying to work with the macro name, not its contents.

          Comment


          • #6
            That is it! Sorry, I forgot to mention that as well. It's nice to know that length should also work in addition to strlen. Thanks Mike and Nick.

            Comment


            • #7
              Many thanks.

              Comment

              Working...
              X