繁体   English   中英

如何将bash中以点分隔的整数序列归零

[英]How to zero pad a sequence of integers seperated with dot in bash

我需要以特定格式来塑造版本。

例如:

V1=1.0.1
V2=4.0.1
V3=3.1.101
...

需要填充0,如下所示:

V1=001.000.001.000
V2=004.000.001.000
V3=003.001.101.000
...

关于我该怎么做的任何想法?

编辑:

我成功使用了printf,如下所示:

printf "%03d.%03d.%03d.000\n" $(echo $V3 | grep -o '[^-]*$' | cut -d. -f1) $(echo $V3 | grep -o '[^-]*$' | cut -d. -f2) $(echo $V3 | grep -o '[^-]*$' | cut -d. -f3)

输出:

003.001.101.000

还有更好的建议吗?

您可以尝试使用awk

awk -F'[=.]' '{                        # Set field delimiter to = and .
   split($0, a, FS, seps)              # Get all elements and separator into an array
   for(i=1;i<=5;i++) {                # Loop though all fields
     if(i>1) 
       a[i]=sprintf("%03d",$i)         # Update the version number with 3 digits
     printf "%s%s", a[i], seps[i]}     # Print the field
     print ""                          # print a newline
}' file

如果版本在bash变量中,则可以使用更简单的awk一种衬板:

V3="3.1.101"; awk -F. '{for(i=1;i<5;i++){$i=sprintf("%03d",$i)}}1' OFS='.' <<<$V3

让我们用sed尝试获取一个文本文件,其中列出了作为输入的版本,名为versions.txt。 为了简单起见,我拆分了说明:

# Add '00' before each sub-version number
sed -i -r 's/([=\.])([0-9])/\100\2/g' versions.txt
# Remove '00' if sub-version number had 3 digits
sed -i -r 's/([=\.])00([0-9]{3})/\1\2/g' versions.txt
# Remove '0' if sub-version number had 2 digits
sed -i -r 's/([=\.])00([0-9]{2})/\10\2/g' versions.txt
# Add the final '.000' after each version
sed -i -r 's/([0-9]{3}\.[0-9]{3}\.[0-9]{3})/\1\.000/g' versions.txt

另一种sed方法:

sed -r 's/\b([0-9]{1})(\.|$)/00\1\2/g;s/\b([0-9]{2})(\.|$)/0\1\2/g;s/(([0-9]{3}\.|$){3})/\1.000/g'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM