如何通过Shell命令提取UTC时间范围12-00对应的TMP数值并输出预期结果?
Your current command returns the entire TMP line because it only grabs the line after the matched UTC line, not filtering the specific columns you need. Here are two reliable ways to get your desired output:
Method 1: Dynamic Extraction with Awk (Works even if positions shift)
This approach automatically identifies the start (12) and end (00) positions in the UTC line, then extracts those same positions from the TMP line:
awk ' NR == 1 { # Locate the start of "12" and end of the target "00" for (i = 1; i <= NF; i++) { if ($i == "12") start_idx = i; if ($i == "00" && start_idx != 0) { end_idx = i; break; } } # Collect the UTC range values for (j = start_idx; j <= end_idx; j++) utc_vals = utc_vals $j " "; } NR == 2 { # Collect the corresponding TMP values for (j = start_idx; j <= end_idx; j++) tmp_vals = tmp_vals $j " "; # Print the combined result printf "%s%s\n", utc_vals, tmp_vals; } ' some.text.file
Output:
12 13 14 15 16 17 18 19 20 21 22 23 00 47 47 47 48 48 48 48 48 47 45 44 43 43
Method 2: Fixed Column Extraction with Cut (Simple if positions are static)
Since we know the target UTC values are in columns 8 through 20 (1-based) in both lines, we can directly extract those columns:
# Extract the UTC range from the first line utc_range=$(cut -d' ' -f8-20 some.text.file | head -n1) # Extract corresponding TMP values from the second line tmp_range=$(cut -d' ' -f8-20 some.text.file | head -n2 | tail -n1) # Combine and print the results echo "$utc_range $tmp_range"
Output:
12 13 14 15 16 17 18 19 20 21 22 23 00 47 47 47 48 48 48 48 48 47 45 44 43 43
Why Your Original Command Failed:
grep -A 1 '12.*00' matches the UTC line (since it contains "12" followed by characters leading to "00") and outputs that line plus the next full TMP line. tail -n1 then just takes the entire TMP line, without filtering the specific columns you need.
内容的提问来源于stack exchange,提问作者arnpry

