我在网上有一个.txt
文件,其中包含以下文字:
"Type": "Internal",
"Category": 1,
"Presentation": 3,
...
我想使用Apps Script来读取该文件的内容,并最终将其保存在包含已修改内容的新文件中。具体来说,我需要删除某些内容的下划线,但保持其余内容不变。
答案 0 :(得分:12)
Apps脚本使用JavaScript编程语言。对于在Google服务器上运行的Apps脚本代码,JavaScript代码将位于.gs
“脚本”文件中。 JavaScript最初是为“客户端”使用而创建的,这意味着它在您已在 计算机(非Google服务器)上打开的浏览器中运行。在客户端JavaScript中,代码被放入HTML <script>
标记中。但是,Apps脚本也使用JavaScript作为服务器端代码,它用于两者。
如果文本文件位于Google云端硬盘中,您可以通过各种方式访问它。一种方法是使用Drive Service
以下是一些可以从Google云端硬盘获取文件的示例代码:
var allFilesInFolder,cntFiles,docContent,fileNameToGet,fldr,
thisFile,whatFldrIdToUse;//Declare all variable at once
whatFldrIdToUse = '123ABC_Put_Your_Folder_ID_here';
fileNameToGet = 'myText.txt';//Assign the name of the file to get to a variable
//Get a reference to the folder
fldr = DriveApp.getFolderById(whatFldrIdToUse);
//Get all files by that name. Put return into a variable
allFilesInFolder = fldr.getFilesByName(fileNameToGet);
Logger.log('allFilesInFolder: ' + allFilesInFolder);
if (allFilesInFolder.hasNext() === false) {
//If no file is found, the user gave a non-existent file name
return false;
};
cntFiles = 0;
//Even if it's only one file, must iterate a while loop in order to access the file.
//Google drive will allow multiple files of the same name.
while (allFilesInFolder.hasNext()) {
thisFile = allFilesInFolder.next();
cntFiles = cntFiles + 1;
Logger.log('File Count: ' + cntFiles);
docContent = thisFile.getAs('text/plain');
Logger.log('docContent : ' + docContent );
};
要查看代码生成的值,请进入“日志”对话框。单击“查看”菜单,然后从菜单中选择“日志”。 Logger.log()
语句将内容打印到日志中。
您为示例提供的内容类似于JSON。您可以使用JSON.parse()将JSON格式的字符串转换为对象。从那里你可以添加或更改值。如果要在将JSON放回文本文件之前将其转换回字符串,可以使用JSON.stringify()
为了在字符串中查找特定字符,您需要学习JavaScript字符串函数。
要替换所有出现的某段文字,您可以使用replace
: