2017-01-21 7 views
0

Как прочитать последнюю строку из текстового файла и скопировать часть этой строки в другой текстовый файл?читать копию последней строки из текстового файла

Чтобы быть более ясным, позволяет сказать, что у нас есть текстовый файл (a.txt), содержащий текст ниже:

11:22:33 : first line text 
11:22:35 : second line text 

Моя потребность заключается в копировании из последней строки «11:22:35: второй текст строки "только текст второй строки" и вставьте эту строку в другой файл txt (b.txt). Перед вставкой файл b.txt должен быть сначала очищен.

ответ

2

Это проще всего сделать делегировать эту задачу команды оболочки вызывается с 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 потерпит неудачу.

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