Luciano Nascimento
Luciano Nascimento

Reputation: 2600

Lua remove first directory from path

How can I remove the first directory from path string (if exists)?

I tried several times with gsub and string.match but I cannot get this working.

Inputs:

/
/tmp/file.txt
/tmp/folder/file2.txt
/tmp/folder/.../file3.txt

Outputs:

/
/file.txt
/folder/file2.txt
/folder/.../file3.txt

Upvotes: 2

Views: 773

Answers (2)

Doyousketch2
Doyousketch2

Reputation: 2147

#! /usr/bin/env lua

dirsep = package .config :sub( 1, 1 )
cwd = '/tmp/folder/file2.txt'
delimeter = { cwd :find( dirsep, 2 ) }
subdir = cwd :sub( delimeter [1] or 1 )

print( subdir )

/folder/file2.txt

Upvotes: 0

Alexander Mashin
Alexander Mashin

Reputation: 4617

local paths = {
    '/',
    '/tmp/file.txt',
    '/tmp/folder/file2.txt',
    '/tmp/folder/.../file3.txt'
}

for _, path in ipairs (paths) do
    local trimmed = path:gsub ('^/[^/]+', '')
    print (trimmed)
end

The necessary regular expression is ^/[^/]+. It is anchored to the beginning of the string and requires at least one non-slash character after, so that / does not match.

Upvotes: 3

Related Questions