如何为计算用两个文件生成0-40000时间步的格式化虚拟数据?
Got it, let's work through this step by step with simple, copy-pasteable commands — no advanced Awk expertise required. We'll generate the missing 0 to 40000 timestep data and prepend it to both files while keeping your original data intact.
Your File1 needs lines formatted like i = X, time = YYYYY.000 where time = i/2, starting from i=0, time=00000.000 up to i=40000, time=20000.000. Here's how to generate and add these lines:
- First, generate the missing header lines with this one-liner (it uses Awk to handle the math and formatting cleanly):
awk 'BEGIN{for(i=0;i<=40000;i++){time=i/2; printf "i = %d, time = %08.3f\n", i, time}}' > temp_file1.txt
This loops from i=0 to i=40000, calculates the corresponding time, and prints each line in the exact format you need (the %08.3f ensures time shows up as 00000.000, 00000.500, etc.).
- Append your original File1 content to this temporary file:
cat your_original_file1.txt >> temp_file1.txt
(Replace your_original_file1.txt with your actual filename.)
- Replace your original File1 with the updated version:
mv temp_file1.txt your_original_file1.txt
For File2, each line corresponds to a timestep, so we'll use your existing line format as a template to generate the missing lines.
- First, save the first line of your original File2 as a template (since all lines follow the same structure):
template=$(head -n 1 your_original_file2.txt)
(Replace your_original_file2.txt with your actual filename.)
- Generate the 40001 missing lines (0 to 40000) by replacing the
iandtimevalues in the template:
awk -v template="$template" 'BEGIN{for(i=0;i<=40000;i++){ time=i/2; new_line=template; gsub(/i = [0-9]+/, "i = "i, new_line); # Adjust this if your i format is different (e.g., `i=[0-9]+` without spaces) gsub(/time = [0-9]+\.[0-9]+/, sprintf("time = %08.3f", time), new_line); # Same here for time format print new_line }}' > temp_file2.txt
Note: If your File2 lines use i=X instead of i = X (no spaces), just change the first gsub pattern to /i=[0-9]+ and the replacement to "i="i. Same for the time pattern if needed.
- Append your original File2 content to the temporary file:
cat your_original_file2.txt >> temp_file2.txt
- Replace your original File2 with the updated version:
mv temp_file2.txt your_original_file2.txt
That's it! Both files will now have all timesteps from 0 to 200000, with the missing 0-40000 steps added at the top in the correct format.
内容的提问来源于stack exchange,提问作者user3292696

