You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Emacs给多个未打开的*.org文件开头添加内容?求对应正则

Add Mode and Coding Lines to the Top of Multiple .org Files in Emacs

Hey there! Let me walk you through how to add those two required lines to the top of all your .org files across multiple directories, and clarify how "start of file" works in Emacs regex.

First: Emacs Regex for "Start of File"

In Emacs regular expressions, the ^ character matches the start of a line. When you run a batch replace (like on multiple files), each file is processed independently—so the first ^ in a file corresponds directly to the absolute start of that file (the very first character position, before the first line of content). No special syntax is needed beyond ^ to target the file's opening.

Solution 1: Batch Replace with replace-regexp-in-files

This is the most straightforward way to handle multiple files across directories:

  1. Press M-x (Alt+x) and type replace-regexp-in-files, then hit Enter.
  2. For the regex prompt, enter ^ (this targets the start of each file).
  3. For the replacement text, paste or type:
    # -*- mode: org -*-
    # -*- coding: utf-8 -*-
    
    
    Note: To insert a newline in the replacement prompt, use C-q C-j (Ctrl+q followed by Ctrl+j) instead of just pressing Enter.
  4. Next, enter the file pattern: *.org to target all Org files.
  5. When asked for the directory to search, input your root directory (e.g., ~/my-org-notes/). To include all subdirectories recursively, append /** to the path (like ~/my-org-notes/**).

Solution 2: Dired Batch Processing

If you prefer a visual approach with Dired:

  1. Open Dired to your root directory with C-x d.
  2. Press % m to mark files matching a pattern, then enter \.org$ to select all .org files.
  3. Press Q to run dired-do-query-replace-regexp.
  4. Enter ^ as the regex, then input the replacement text (same as Solution 1, using C-q C-j for newlines).
  5. You’ll get a prompt for each file—press y to replace, n to skip (useful if some files already have the lines).

Avoid Duplicate Lines (Optional)

If some files already have the mode/coding lines, you can tweak the regex to skip them. Use this regex instead of ^:

^\(?!# -*- mode: org -*-\)

This is a negative lookahead that only matches the start of files not already starting with the mode line. Note: Emacs supports this syntax when using extended regexes—if you run into issues, test on a few files first to ensure it works as expected.

Pro Tip

Always back up your files first, or test the replacement on a small set of files before running it on your entire collection. Better safe than sorry!

内容的提问来源于stack exchange,提问作者147pm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:21:16