Это проще всего сделать делегировать эту задачу команды оболочки вызывается с do shell script
:
# 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'
Использование раковины для краткого, но довольно загадочного решения.
Вот 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
с файлом ссылка, конечная новая строка (\n
) добавляется автоматически, когда вы нацеливаете файл [объект] напрямую.
Однако это работает только в том случае, если целевой файл уже существует, что обеспечивает вспомогательная команда do shell script
(с помощью стандартной утилиты touch
). Если файл еще не существует, «литье» пути к файлу POSIX file
потерпит неудачу.