如何从Bash脚本输出中提取最后16个数字并转为逗号分隔格式
Absolutely! There are a few clean, reliable ways to grab just the last 16 Segment Data numbers and format them into a comma-separated string. Let’s break down the best approaches based on your workflow:
1. Extend Your Existing Grep Workflow (Simplest)
Since you’re already using grep to extract all numbers, you just need to filter for the last 16 and join them with commas. This is straightforward and leverages tools you’re already familiar with:
# First capture the full output properly (always quote variables to preserve newlines!) MyOut="$("./my_test_file.sh")" # Extract all numbers, keep the last 16, then join with commas numbers=$(echo "$MyOut" | grep -o -E '[0-9]+' | tail -n 16 | paste -sd ',' -)
How it works:
tail -n 16: Grabs the final 16 lines of the grep output (each number is on its own line in your script’s output)paste -sd ',' -: Merges these 16 lines into a single string, separated by commas
2. Targeted Awk Approach (More Efficient)
If you want to avoid multiple pipe operations, awk can handle the entire process in one go—directly targeting the Segment Data section and grabbing the last 16 entries:
MyOut="$("./my_test_file.sh")" numbers=$(echo "$MyOut" | awk ' /Segment Data:/ { flag = 1; next } # Start capturing lines after this header flag { arr[++count] = $0 } # Store each Segment Data number in an array END { # Print the last 16 elements, separated by commas for (i = count - 15; i <= count; i++) { printf "%s%s", arr[i], (i == count ? "" : ",") } } ')
This method skips irrelevant lines entirely and only processes the Segment Data section, making it faster for larger outputs.
3. Pure Regex (Using Perl-Compatible Patterns)
If you specifically want to use a regex to match the final 16 numbers (note: this relies on the numbers being the last content in your output), you can use grep -P (Perl-compatible regex) to target them:
MyOut="$("./my_test_file.sh")" numbers=$(echo "$MyOut" | grep -o -P '(?:\b[0-9]+\b\s*){16}$' | grep -o -E '[0-9]+' | paste -sd ',' -)
How it works:
(?:\b[0-9]+\b\s*){16}$: Matches 16 consecutive number-word boundaries followed by optional whitespace, anchored to the end of the output- The second
grepcleans up any leftover whitespace, thenpastejoins the numbers with commas
Important Note:
Always use double quotes around variables like "$MyOut" to preserve newlines and whitespace—omitting them will collapse all output into a single line, which can break your number extraction logic.
内容的提问来源于stack exchange,提问作者Ash SDR

