使用 sed 按升序附加值

问题描述 投票:0回答:1

我有一个配置文件,我需要按升序附加版本。为此我编写了一个 shell 脚本。正在附加值,但位置不正确。

Config file

[version]
        1.0.0.0, 1.0.1.0, 1.0.2.0, 1.0.3.0, 1.0.3.1, 1.0.4.0, 1.0.4.1, 1.0.5.0, 1.0.5.1, 1.0.6.0, 1.0.6.1, 1.0.6.2, 1.0.7.0, 1.0.7.1,  1.2.2.8,  1.2.2.9, 1.2.2.10, 1.2.2.1, 1.2.3.0, 1.3.0.0, 1.2.3.1, \

假设我通过了1.0.7.2,那么它应该追加到1.0.7.1之后,基本上按升序排列。

这是我为实现此目的而编写的 shell 脚本

#!/bin/bash
# Define the value to append
value_to_append="$1"
# Path to the configuration file
config_file="app.config"
line_number=$(grep -n "\[version\]" "$config_file" | cut -d':' -f1)
# Append the value after the line_number
sed -i "${line_number}a \ \ \ \ \ \ \ \ $value_to_append," "$config_file"

使用此脚本,值会附加在开头,而不是按升序排列。我应该在脚本中更改什么才能按正确的顺序定位值。

bash awk sed
1个回答
0
投票

使用 GNU

awk
和 GNU
sort
:

#!/bin/bash
# Path to the configuration file
config_file="app.config"
awk -v v="$1" '
  BEGIN { cmd = "sort -V" }
  go {
    n = patsplit($0, a, @/[0-9]+(\.[0-9]+)*/, s)
    a[n + 1] = v; s[n + 1] = s[n]; s[n] = ", "
    for(i = 1; i <= n + 1; i++) print a[i] |& cmd
    close(cmd, "to")
    i = 0
    while(cmd |& getline) printf("%s%s", s[i++], $0
    print s[n + 1]
    go = 0; next
  }
  /^\[version\]$/ {go = 1} 1' "$config_file"
© www.soinside.com 2019 - 2024. All rights reserved.