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.txtin 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-iflag edits the file directly in-place.1itells sed to insert the textTitlebefore 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
$filein 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
相关产品推荐
相关产品推荐

