bash - Infile 更改项目的填充

标签 bash

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

la-que-no-podia-capitulo-1
la-que-no-podia-capitulo-25
la-que-no-podia-capitulo-30

并希望达到这一步

la-que-no-podia-capitulo-001
la-que-no-podia-capitulo-025
la-que-no-podia-capitulo-030

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

  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
    

    (利用 https://stackoverflow.com/a/63551084/10906045 )

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

  2. AWK

    awk -F'-' '{ printf "%04d: \n", $NF }' output_downloads >output_downloads2
    head output_downloads2
    
    0001: 
    0002: 
    0003: 
    0004: 
    0050: 
    

    我无法提取第一部分。

最佳答案

使用awk

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

这是实际的 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])
}

使用 Bash ERE:

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

或者使用 POSIX shell:

#!/usr/bin/env sh

while IFS= read -r line || [ "$line" ]; do
  IFS=-
  # Split line on dashes and fills the arguments array
  # shellcheck disable=SC2086 # Intended word splitting
  set -- $line
  # Format print arguments followed by dash except last one
  while [ $# -gt 1 ]; do
    printf '%s-' "$1"
    shift
  done
  # Format print last argument as 0-padded, 3 digits integer and newline
  printf '%03d\n' "$1"
done <inputfile

关于bash - Infile 更改项目的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63552368/

相关文章:

python - 解析模板然后生成作业 dsl 文件的脚本

linux - 通过 bash 从其他用户发送 screen 内命令

bash - sed 到 grep 两个模式之间的字符串

Bash 脚本中 $0 的意外值

bash - 从文件中读取值,增加或更改它们并将它们再次存储在同一位置

bash - 并行运行多个进程但在 bash 中一起退出

linux - 巴什 : Sum size of same name directories

linux - 如何在 bash 中记录输出并同时在终端中看到它?

bash - 在同一命令中删除重复行并覆盖文件

bash - 如何从命令行进行递归查找和替换?