Regex найти, переместить и заменить

У меня есть несколько файлов уценки, которые начинаются с шаблона 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

Я подумал о логике (используя регулярные выражения) того, как я думаю, что это должно быть сделано, но я не знаю, как это реализовать. Вот что я придумал:

  • find \ w + (- \ w +) +. jpg [соответствует имени файла изображения, т.е. в данном случае Miniarchi-1.jpg]
  • хранить в переменной $ img
  • найти postheaderimage:
  • заменить на postheaderimage: $ img
  • find alt: \ s \ w. * [соответствует изображению alt, т.е. в этом случае минимальная архитектура]
  • хранить в переменной $ alt
  • найти \ s {2} — \ n \ s {4} img: \ s. {1,} \ n \ s {4} alt: \ s. {1,} [сопоставить все, что находится под постголовным изображением:]
  • заменить на $ alt

Я думаю, что это можно решить с помощью appleScript, или, может быть, даже php, но я не знаю как.
Если потребуется дополнительная информация, о которой я не упомянул, пожалуйста, спросите, и я буду рад уточнить.

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

Поверьте мне, это действительно быстро! Пожалуйста, попробуйте с копиями! Скрипт переписывает исходные файлы!

0

Другие решения

Других решений пока нет …