string.gsub()在两个路径上无法工作

我在一个包含子目录和Markdown文件的"content"文件夹的目录树中进行了循环。然后我需要知道这些Markdown文件相对于"content"文件夹的路径。

在bash脚本中,我会像这样做:

CONTENT_PATH="/home/myusr/apps/myapp/content"
file_path="/home/myusr/apps/myapp/content/file/pgp.md"

echo "${file_path#$CONTENT_PATH}"
# /file/pgp.md

所以在Lua中,我没有找到类似于这样的东西,所以我尝试使用string.gsub()

print(string.gsub(file_path, CONTENT_PATH, ""))
-- /home/myusr/apps/myapp/content/file/pgp.md 0

但它没有工作,似乎我的CONTENT_PATH字符串不匹配,我不知道为什么?

print(CONTENT_PATH)
-- /home/hs0ucy/_01_http/fakestache-lua/content

print(file_path)
-- /home/hs0ucy/_01_http/fakestache-lua/content/file/pgp.md

谢谢!

PS:我是Lua的新手。

点赞
用户211176
用户211176

Lua 中连字符是一个特殊字符,需要像这样进行转义:%-

我通过缓慢地将CONTENT_PATH逐渐延长直到它无法工作来发现这一点。好老的二分法!

编辑:如果您无法修改CONTENT_PATH,但确信file_path中包含CONTENT_PATH

contentPathLen = string.len(CONTENT_PATH)
print(string.sub(file_path, contentPathLen + 1))
--输出:/file/pgp.md

或者,如果您需要验证file_path是否以CONTENT_PATH开头:

base = string.sub(file_path, 0, contentPathLen)
if base == CONTENT_PATH then
    print("file_path 是在 CONTENT_PATH 下的")
end
2017-10-16 16:14:30