技术求助:限定数量的文件字符替换实现方案咨询
Got it, let's break this down step by step. The core goal is twofold: first, extract the exact number of * from your first file, then replace dashes (-) in the pattern file with those *—stopping once we've used up all the asterisks.
First, Clarify the Inputs
Let's define our files for clarity:
stars.txt: Contains|**********|(8 asterisks total, once we strip the|characters)pattern.txt: Contains- /-\ /---\ /-----\ /-------\
Approach Overview
- Extract and count the asterisks: Pull all
*fromstars.txtand note how many there are (8 in this case). - Replace dashes sequentially: Iterate through the pattern file, replacing each
-with a*until we've used every single asterisk fromstars.txt. Any remaining dashes stay as-is.
Implementation Options
Option 1: Use Awk (Clean, Scalable)
Awk is perfect for this kind of character-level processing. Save this script as replace_stars.awk:
BEGIN { # Read the stars file and extract only asterisks while ((getline line < "stars.txt") > 0) { raw_stars = raw_stars line } gsub(/[^*]/, "", raw_stars) # Remove everything except * total_stars = length(raw_stars) used_stars = 0 } # Process each line in the pattern file { output_line = "" # Loop through each character in the line for (i = 1; i <= length($0); i++) { current_char = substr($0, i, 1) # Replace dash with star only if we have stars left if (current_char == "-" && used_stars < total_stars) { output_line = output_line "*" used_stars++ } else { output_line = output_line current_char } } print output_line }
Run it with:
awk -f replace_stars.awk pattern.txt
Option 2: Bash + Sed (Quick, No External Script Files)
If you prefer a one-liner-style approach using basic shell tools:
# Count the total asterisks in stars.txt star_count=$(grep -o "*" stars.txt | wc -l) # Build a sed command to replace the first N dashes with stars sed_command="" for ((i=0; i<star_count; i++)); do sed_command="$sed_command s/-/*/" done # Execute the replacement sed "$sed_command" pattern.txt
Expected Output
With your input files, the result will be:
* /*\ /***\ /***--\ /-------\
Let's verify the asterisk count: 1 (first dash) + 1 (from /-\) + 3 (from /---\) + 3 (first three from /-----\) = 8, which matches exactly the number of asterisks in stars.txt.
Edge Cases to Consider
- If
stars.txthas 0 asterisks: The pattern file remains unchanged. - If
stars.txthas more asterisks than there are dashes inpattern.txt: All dashes get replaced, and any extra asterisks are ignored (since we can't use them).
内容的提问来源于stack exchange,提问作者Nauman Shahid

