Infile 更改项目的填充

Fra*_*eny 2 bash

目前正在解析一些网站以提高我的 Unix Bash 技能。已提取一个具有以下格式的文件

la-que-no-podia-capitulo-1
la-que-no-podia-capitulo-25
la-que-no-podia-capitulo-30
Run Code Online (Sandbox Code Playgroud)

并且想要到达这一步

la-que-no-podia-capitulo-001
la-que-no-podia-capitulo-025
la-que-no-podia-capitulo-030
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?我尝试过不同的方法:

  1. Bash 正则表达式

    x='a-que-no-me-dejas-capitulo-10'
    re='((([[:alpha:]]+(-))+)[[:digit:]]+)'
    if [[ $x =~ $re ]]
    then
        echo The regex matches!
        echo ${BASH_REMATCH[*]}
    fi
    
    Run Code Online (Sandbox Code Playgroud)

    (利用/sf/answers/4448575911/

    但不幸的是它没有分割最后一个数字。

  2. AWK

    awk -F'-' '{ printf "%04d: \n", $NF }' output_downloads >output_downloads2
    head output_downloads2
    
    0001: 
    0002: 
    0003: 
    0004: 
    0050: 
    
    Run Code Online (Sandbox Code Playgroud)

    我无法提取第一部分。

Léa*_*ris 5

用 awk

awk '{ match($0, /(.*-)([[:digit:]]+)$/, m); printf("%s%03d\n", m[1], m[2])}' inputfile
Run Code Online (Sandbox Code Playgroud)

这是实际的 awk 脚本:

{
  # Regex match whole line with 2 capture groups
  match($0, /(.*-)([[:digit:]]+)$/, m)

  # Format print both captured groups
  printf("%s%03d\n", m[1], m[2])
}
Run Code Online (Sandbox Code Playgroud)

使用 Bash ERE:

{
  # Regex match whole line with 2 capture groups
  match($0, /(.*-)([[:digit:]]+)$/, m)

  # Format print both captured groups
  printf("%s%03d\n", m[1], m[2])
}
Run Code Online (Sandbox Code Playgroud)

或者使用 POSIX shell:

while IFS= read -r || [[ $REPLY ]]; do
 # Regex match whole line with 2 capture groups
 [[ $REPLY =~ (.*-)([[:digit:]]+)$ ]] || :

 # Format print both captured groups
 printf '%s%03d\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
done <inputfile
Run Code Online (Sandbox Code Playgroud)