如何从文本文件中读取最后一行并将此行的一部分复制到另一个文本文件?
更清楚地说,我们有一个包含以下文字的文本文件(a.txt):
11:22:33 : first line text
11:22:35 : second line text
我需要从最后一行“11:22:35:第二行文本”复制“第二行文本”并将此字符串粘贴到另一个txt文件(b.txt)。 在粘贴b.txt文件之前必须先清除它。
答案 0 :(得分:2)
最简单的做法是将此任务委托给使用do shell script
调用的shell命令:
# Determine input and output file paths.
# Note: Use POSIX-format paths ('/' as the separator).
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Use a shell command to extract the last line from the input file using `sed`
# and write it to the output file.
do shell script "sed -n '$ s/.*: \\(.*\\)/\\1/p' " & quoted form of inFile & ¬
" > " & quoted form of outFile
注意:嵌入式sed
命令如下所示,将其嵌入AppleScript字符串中所需的额外\
个实例已删除:
sed -n '$ s/.*: \(.*\)/\1/p'
使用shell可以提供简洁但有点神秘的解决方案。
这里有 AppleScript等效版,它更易于阅读,但也更加详细:
此变体逐行读取输入文件 :
# Determine input and output file paths.
# Note: Use POSIX-format paths ('/' as the separator).
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Read the input file line by line in a loop.
set fileRef to open for access POSIX file inFile
try
repeat while true
set theLine to read fileRef before linefeed
end repeat
on error number -39 # EOF
# EOF, as expected - any other error will still cause a runtime error
end try
close access fileRef
# theLine now contains the last line; write it to the target file.
set fileRef to open for access POSIX file outFile with write permission
set eof of fileRef to 0 # truncate the file
write theLine & linefeed to fileRef # Write the line, appending an \n
close access fileRef
如果读取输入文件作为一个整体 是可以接受的,那么可以采用更简单的解决方案:
set inFile to "/path/to/a.txt"
set outFile to "/path/to/b.txt"
# Read the input file into a list of paragraphs (lines) and get the last item.
set theLastLine to last item of (read POSIX file inFile using delimiter linefeed)
# Write it to the target file.
do shell script "touch " & quoted form of outFile
write theLastLine to POSIX file outFile
请注意写入目标文件的简化方法,无需明确打开和关闭文件
此外,与将write
与文件引用一起使用时不同,当您直接定位文件[object]时会自动添加尾随换行符(\n
)。
但是,这仅在目标文件已存在时才有效,这是辅助do shell script
命令确保的(通过标准实用程序touch
)。
如果文件还没有存在," cast" POSIX file
的文件路径将失败。
答案 1 :(得分:1)
了解"开放访问"的细节非常方便。这是你的剧本:
set sourcePath to (path to desktop as string) & "a.txt"
set destinationPath to (path to desktop as string) & "c.txt"
-- set lastParagraph to last paragraph of (read file sourcePath) -- could error on unix text files
set lastParagraph to last item of (read file sourcePath using delimiter linefeed)
set fileReference to open for access file destinationPath with write permission
try
set eof of fileReference to 0 -- erases the file
write lastParagraph to fileReference
close access fileReference
on error
close access fileReference
end try