如何用sed命令将行尾数字移至行首?
Got it, let's get this sorted for you! The original command you have works for leading numbers because it's targeting digits at the start of the line. To move trailing digits to the front, we just need to adjust the regular expression to target digits at the end of the line instead.
The Correct sed Command
Use this modified command to shift all trailing numbers to the beginning of each line:
sed -E 's/(.*)([0-9]+)$/\2\1/' file
How It Works
Let's break down the regex to understand why this works:
(.*): Captures all characters (the non-trailing part of the line) into the first group. This will match everything up to the last sequence of digits.([0-9]+)$: Captures one or more digits at the end of the line ($anchors the match to the line's end) into the second group.\2\1: Swaps the two groups, putting the captured digits (group 2) first, followed by the original non-digit content (group 1).
Test Example
If your input file contains:
example123
example321
example2920
Running the command will output:
123example
321example
2920example
Edge Case Note
If your lines have digits in the middle (e.g., test123abc456), this command will only move the trailing digits (456) to the front, resulting in 456test123abc. If you needed to move all digits in the line to the front, that would require a different approach—but based on your example, this should be exactly what you need.
内容的提问来源于stack exchange,提问作者Uni VPS

