求助:使用sed提取Bash脚本参数中的纯数字及脚本返回值异常问题
Hey there! Let's work through your two Bash scripting questions step by step—sounds like you're trying to parse numeric values from input parameters and hitting a snag with getting the full sequence instead of just 1.
To pull out all digits from every input parameter passed to your script, you can use sed to globally strip out any non-numeric characters. Here are a couple of practical approaches:
Option 1: Extract digits from each parameter individually
If you want to process each parameter separately and get numeric values per input:
#!/bin/bash # Loop through all input parameters for param in "$@"; do # Use sed to remove all non-digit characters numeric_value=$(echo "$param" | sed 's/[^0-9]//g') # Only print if there are digits in the parameter if [[ -n "$numeric_value" ]]; then echo "Extracted from '$param': $numeric_value" fi done
The sed command s/[^0-9]//g works like this:
s/...//: Replaces the matched pattern with nothing (deletes it)[^0-9]: Matches any character that is NOT a digit (0-9)g: Global flag—ensures all non-digit characters are removed, not just the first one
Option 2: Combine all digits from all parameters into one string
If you want to merge all numeric characters from every parameter into a single sequence:
#!/bin/bash # Join all parameters into one string, then strip non-digits all_numbers=$(echo "$*" | sed 's/[^0-9]//g') echo "Combined numeric result: $all_numbers"
Using $* instead of $@ joins all parameters into a single space-separated string before processing, making it easy to capture all digits at once.
1 instead of 1234567 The most likely issues here are either missing a critical sed flag or only processing part of your input. Let's break down common mistakes and their fixes:
Common mistake 1: Missing the global (g) flag
If your script uses something like this:
# Wrong: Only removes the FIRST non-digit character result=$(echo "$1" | sed 's/[^0-9]//') echo "$result"
This would stop at the first non-digit character it encounters. For example, input like 1abc234567 would return 1 instead of the full sequence. Adding the g flag fixes this by removing all non-digits:
# Correct: Removes ALL non-digit characters result=$(echo "$1" | sed 's/[^0-9]//g') echo "$result"
Common mistake 2: Only processing the first parameter
If your script is only looking at $1 (the first input parameter) but your numeric sequence is spread across multiple parameters, you'll only get digits from the first one. Use $* or loop through $@ to capture all inputs, like in the examples above.
Sample fixed script
Here's a complete example that will output 1234567 if your input parameters contain those digits (e.g., ./script.sh a1 b23 c4567):
#!/bin/bash full_numeric=$(echo "$*" | sed 's/[^0-9]//g') echo "$full_numeric"
Run it with your test input, and it should return the full sequence instead of just 1.
内容的提问来源于stack exchange,提问作者Andrei

