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

CentOS 6 64位:如何给/home目录下批量TXT文件添加指定首行?

Solution for Prepend "Title" to All .txt Files in /home (CentOS 6)

Here are two reliable methods to add the line "Title" as the first line to every .txt file in your /home directory, preserving the original filenames.

Method 1: Using sed (Simplest Approach)

The sed utility can edit files in-place and insert text at the beginning with just one command per file. Run this in your terminal:

for file in /home/*.txt; do
    # Skip if no .txt files exist (avoids acting on the literal wildcard string)
    [ -f "$file" ] || continue
    # Insert "Title" as the first line
    sed -i '1i Title' "$file"
done

Explanation:

  • for file in /home/*.txt: Iterates over all files ending with .txt in the /home directory.
  • [ -f "$file" ] || continue: Ensures we only process actual files (skips the loop entirely if there are no .txt files present).
  • sed -i '1i Title' "$file": The -i flag edits the file directly in-place. 1i tells sed to insert the text Title before line 1, making it the new first line of the file.

Method 2: Using Temporary Files (Safer for Large/Delicate Files)

If you're working with very large files or want to eliminate any risk of data corruption from in-place editing, use this method which creates a temporary file first:

for file in /home/*.txt; do
    [ -f "$file" ] || continue
    # Create a temporary file starting with "Title"
    echo "Title" > "$file.tmp"
    # Append the original file's content to the temp file
    cat "$file" >> "$file.tmp"
    # Replace the original file with the temp file (preserves permissions)
    mv "$file.tmp" "$file"
done

Explanation:

  • echo "Title" > "$file.tmp": Writes the "Title" line to a temporary file with the same base name as the original.
  • cat "$file" >> "$file.tmp": Adds all content from the original file to the end of the temporary file, creating the modified version we want.
  • mv "$file.tmp" "$file": Replaces the original file with the modified temporary file, keeping the original filename and file permissions intact.

Key Notes:

  • Both methods handle up to 300 files easily—no performance issues here for the stated limit.
  • If your filenames contain spaces (though your example doesn't include them), wrapping $file in double quotes ensures the loop processes each file correctly.
  • As a best practice, always back up important files before running bulk edits like this, just to be safe!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:21:14