이 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
으로 실패합니다.