我有很多以yaml模式开头的降价文件,例如:
---
title: Miniarchi
postheaderimage:
-
img: Miniarchi-1.jpg
alt: Minimal Architecture
class: center
categories:
- Design
tags:
- Architecture
- Illustration
- Miniarchi
---
我正在处理并希望修改所有文件的部分是:
postheaderimage:
-
img: Miniarchi-1.jpg
alt: Minimal Architecture
我想要的是:
postheaderimage: Miniarchi-1.jpg
alt: Minimal Architecture
我已经想到了我认为应该如何做的逻辑(使用正则表达式),但我不知道如何实现它。这就是我提出的:
我认为这可以使用applescript,甚至是php解决,但我不知道如何。
如果需要更多我尚未提及的信息,请询问,我们将很乐意澄清。
答案 0 :(得分:0)
你要求提供一个Applescript,用真正纯粹的Applescript解决这个任务很有趣:
set my_test_file to (path to desktop as string) & "TEST.txt"
tidyUpMyYamlFile(my_test_file)
on tidyUpMyYamlFile(yaml_path)
-- accessing the file's contents, storing it to fh_content
try
set fh to open for access yaml_path
set fh_content to (read fh)
close access fh
on error
try
close access fh
end try
return
end try
-- repairing the postheaderimage part
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "postheaderimage:
-
img:"
set textParts to text items of fh_content
set AppleScript's text item delimiters to "postheaderimage:"
set new_fh_content to textParts as text
set AppleScript's text item delimiters to otid
set fh_content_Lines to paragraphs of new_fh_content
-- repairing the indentation for the word alt: (after the postheaderimage-line only)
repeat with lineNo from 1 to count fh_content_Lines
set altOffset to offset of "alt:" in (item lineNo of fh_content_Lines)
-- this line contains the word "alt:"
if altOffset > 0 then
try
-- the line before starts with the word "postheaderimage:"
if item (lineNo - 1) of fh_content_Lines starts with "postheaderimage:" then
set oldLineContent to item lineNo of fh_content_Lines
set item lineNo of fh_content_Lines to text altOffset thru -1 of oldLineContent
end if
end try
end if
end repeat
-- building new file content, line endings defined by line feed (Ascii 10)
set AppleScript's text item delimiters to ASCII character 10
set new_fh_content to fh_content_Lines as text
set AppleScript's text item delimiters to otid
-- writing the new content to the old file
set fh to open for access yaml_path with write permission
set eof fh to 0
write new_fh_content to fh
close access fh
end tidyUpMyYamlFile
相信我,它真的很快!请尝试复制!该脚本会覆盖源文件!