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

批量修改文本文件首行:依据密钥文件匹配对应个体名称写入

Got it, let's break down how to solve this problem. You’ve got 100 text files (File1 to File100) all with the same header, plus a keyfile that maps each filename to a specific individual’s name. The goal is to add that corresponding individual name to the start of the first line in each file. Here are two solid approaches depending on your operating system and comfort level:

Bash Script (Great for Linux/macOS)

First, double-check your keyfile format: each line should pair a filename with its individual name, separated by whitespace (e.g., File1 JohnDoe, File2 JaneSmith). If names have spaces, use tabs as separators instead of spaces to avoid splitting names incorrectly.

  1. Create a new file named prepend_names.sh and paste this script:
#!/bin/bash

# Use tabs as separators if your individual names have spaces (uncomment below)
# IFS=$'\t'

while read -r filename individual; do
    # Skip empty lines in the keyfile
    [[ -z "$filename" ]] && continue
    
    # Only process existing files to avoid errors
    if [[ -f "$filename" ]]; then
        # Prepend the individual name to the first line (adds a space after the name)
        sed -i "1s/^/$individual /" "$filename"
        echo "Updated: $filename"
    else
        echo "Warning: $filename not found — skipping"
    fi
done < keyfile
  1. Make the script executable with this command:
chmod +x prepend_names.sh
  1. Run it in the same directory as your files and keyfile:
./prepend_names.sh

How this works:

  • read -r filename individual splits each keyfile line into the filename and individual name.
  • sed -i "1s/^/$individual /" edits the first line (1) of the file, inserting the individual name at the start (^) followed by a space to keep it separated from the existing header.

Python Script (Cross-Platform: Windows/macOS/Linux)

This is perfect if you’re not comfortable with bash, or if you need to run this on Windows. It handles spaces in names smoothly as long as your keyfile uses tabs (or you adjust the separator).

  1. Create a file named prepend_names.py with this code:
def add_individual_names(keyfile_path):
    # Build a map of filenames to individual names from the keyfile
    filename_to_name = {}
    with open(keyfile_path, 'r', encoding='utf-8') as keyfile:
        for line_num, line in enumerate(keyfile, 1):
            line = line.strip()
            if not line:
                continue  # Skip empty lines
            
            # Split on tab (use ' ' instead if your keyfile uses spaces and names have no spaces)
            parts = line.split('\t', 1)
            if len(parts) != 2:
                print(f"Skipping invalid line {line_num}: {line}")
                continue
            
            filename, individual = parts
            filename_to_name[filename] = individual.strip()

    # Process each file in the map
    for filename, individual in filename_to_name.items():
        try:
            with open(filename, 'r', encoding='utf-8') as txt_file:
                lines = txt_file.readlines()
            
            # Prepend the name to the first line (if the file isn't empty)
            if lines:
                lines[0] = f"{individual} {lines[0]}"
            
            # Write the modified content back to the file
            with open(filename, 'w', encoding='utf-8') as txt_file:
                txt_file.writelines(lines)
            
            print(f"Successfully updated: {filename}")
        except FileNotFoundError:
            print(f"Warning: {filename} doesn't exist — skipping")
        except Exception as e:
            print(f"Error processing {filename}: {str(e)}")

if __name__ == "__main__":
    add_individual_names("keyfile")
  1. Run the script using Python (make sure Python is installed):
python prepend_names.py

Or on some systems:

python3 prepend_names.py

How this works:

  • It first reads the keyfile into a dictionary, so we can quickly look up which name belongs to which file.
  • For each file, it reads all lines, modifies the first line to include the individual name, then writes the updated content back.

Critical Notes Before You Start

  • Always back up your files first! Any script that modifies files can have unexpected outcomes if something goes wrong — a copy of your original files will save you a headache.
  • If your individual names have spaces, ensure your keyfile uses tabs to separate filenames and names. If you must use spaces, adjust the split logic in the script (comments explain how).
  • Both scripts skip empty lines in the keyfile and warn you if a listed file doesn’t exist, so you won’t waste time troubleshooting missing files.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:26:43