You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用sed命令将行尾数字移至行首?

Fixing the sed Command to Move Trailing Numbers to Line Start

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:26:56