2017-01-21 5 views
0

텍스트 파일의 마지막 줄을 읽고이 줄의 일부를 다른 텍스트 파일에 복사하는 방법은 무엇입니까?텍스트 파일의 마지막 줄 읽기 복사

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

내 필요 11시 22분 35초 마지막 줄에 "복사하는 것입니다 :

더 명확하게하기 위해 우리는 텍스트 파일 (a.txt이)가 말 아래의 텍스트를 포함 할 수 있습니다 초 줄 텍스트 "를"두 번째 줄 텍스트 "로 만들고이 문자열을 다른 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' 

셸을 사용하면 간결하면서도 다소 난감한 솔루션이됩니다. 여기

는 쉽게 읽을 수 동등한 애플 스크립트,하지만 훨씬 더 자세한 정보 :

# 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)이 자동으로 추가됩니다.

그러나 보조 파일 이 보장하는 대상 파일이 이미있는 경우에만 작동합니다 (표준 유틸리티 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 
관련 문제