如何用Awk/Bash将行首数字串移至行尾?
Got it, let's tackle this problem where we need to shift leading digits from the start of each word to its end. Below are practical solutions for common programming languages and command-line tools:
Python
Using regular expressions is the cleanest approach here. We can capture the leading digits and the rest of the word, then swap their positions:
import re input_text = "123example 321example 34292example" output_text = re.sub(r'(\d+)(\w+)', r'\2\1', input_text) print(output_text) # Output: example123 example321 example34292
Note:
If your words include non-alphanumeric characters (like 123example!), adjust the regex to capture everything up to the next space instead:
output_text = re.sub(r'(\d+)([^ ]+)', r'\2\1', input_text)
This will turn 123example! into example!123.
JavaScript
Similar to Python, we use a regex with global replacement to handle all words in the string:
const inputStr = "123example 321example 34292example"; const outputStr = inputStr.replace(/(\d+)(\w+)/g, "$2$1"); console.log(outputStr); // Output: example123 example321 example34292
The g flag ensures we replace every matching word, not just the first one.
Bash (Using sed)
For command-line processing, sed is perfect. We'll use extended regular expressions to swap the digit and word parts:
echo "123example 321example 34292example" | sed -E 's/([0-9]+)([^ ]+)/\2\1/g'
Running this will output the desired string directly in your terminal.
内容的提问来源于stack exchange,提问作者Uni VPS

