设置工厂9-检查文件中的字符串

时间:2019-04-09 16:03:24

标签: scripting setup-factory

我是Lua的100%新用户,需要一种方法来检查我的etc/hosts文件中的字符串。我发现的其他帖子涉及字符串搜索和逐行读取文件。

这是我的一些脚本,是我在此处找到的一些示例的组合:

file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
function check(file)
    if file.match(str, "nbs") then
        file:close()
        Screen.Next();
    else            
        file:write("\n", %UserIP%, " nbs document")
        file:close()
        Screen.Next();
        end
end;

您会看到我正在文件hosts中搜索字符串nbs。如果存在,我想继续。如果没有,我计划用新行附加文件。 当我将其输入到Lua Shell中时,以上内容似乎无济于事。

编辑1:;添加完整脚本;这是完整的原始脚本加上我的补充内容

-- These actions are performed when the Next button is clicked.

-- from _SUF70_Global_Functions.lua:
-- is the "Name:" field empty?
if(g_EditFieldIsEmpty(CTRL_EDIT_01)) then

    -- the name field is empty...tell the user that it's a required field
    -- and remain on this screen (don't advance to the next one)

    -- "Invalid Entry"
    local strTitle = SetupData.GetLocalizedString("MSG_INVALID_ENTRY");

    -- get the label for the "Name:" edit field (since it may have been translated)
    local strFieldName = DlgStaticText.GetProperties(CTRL_STATICTEXT_LABEL_01).Text;

    -- strip off the trailing ":" (if present)
    strFieldName = String.TrimRight(strFieldName, ":");

    -- "The <fieldname> field cannot be empty."
    local strPrompt = SetupData.GetLocalizedString("MSG_THE")
                    ..strFieldName
                    ..SetupData.GetLocalizedString("MSG_FIELD_CANNOT_BE_EMPTY");

    Dialog.Message(strTitle, strPrompt, MB_OK, MB_ICONEXCLAMATION, MB_DEFBUTTON1);
else
    --andrew you added the lines below
    file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
    function check(file)
        if file.match(str, "test") then
            file:close()
            Screen.Next()
        else            
            file:write("\n", "test")
            file:close()
            Screen.Next();
        end
    end;
    -- the "Name:" field isn't empty...so
    -- advance to the next screen
--  Screen.Next();
end;

2 个答案:

答案 0 :(得分:1)

这最终成为我正在寻找的解决方案:

ip = SessionVar.Expand("%UserIP%")
result = TextFile.ReadToString(SessionVar.Expand("%SystemFolder%\\drivers\\etc\\hosts"));
if string.match(result, "nbs") then
    Screen.Next()
else
    file = io.open("C:\\Windows\\System32\\drivers\\etc\\hosts", "a")
    file:write("\n", ip, " nbs document")
    file:close()
    Screen.Next()
end

在这种情况下,我使用的是内置函数的应用程序。这些似乎也使用了C,因此它们无法在Lua shell中工作。

答案 1 :(得分:0)

您的代码创建一个文件句柄并定义一个函数check()。

如果要执行更多操作,则必须添加更多内容。就像检查函数一样。

一旦调用check,您很可能会遇到脚本错误,因为调用了本机Lua中不存在的函数file.match。

file = io.open("C:\Windows\System32\drivers\etc\hosts", "a")
-- this loop will give you each line of the file as a string and you can use string.match
for line in file:lines() do
  if line:match("nbs") then
    print("I found one!!")
  end
end

我确定您可以从这里拿走它。请参阅https://www.lua.org/manual/5.3/manual.html#6.8