2016-11-11 53 views
2

我是shell脚本初学者,我的代码有点麻烦。如何使用shell脚本在数组中格式化字符串?

我的目标是有规模控制和我的数组数字格式“MyString的”

#!/bin/bash 
mystring="333,4444,333,333,4444,333,333" 
expectedValue=4 
addLeftZero() { 
     if [ $myCount -eq $expectedValue ] 
     then 
      #the number has the correct size 
     else 
      #this is where I have to prepend "0" until the number has the expected lenght, 
      #for example the number "333" will be "0333" 
     fi 
      #here i have to return the full array with the mods 
    } 
IFS=',' read -ra ADDR <<< "$mystring" 
    for i in "${ADDR[@]}"; do 
     myCount=${#i} 
     addLeftZero $i 
     return $i 
    done 

0333,4444,0333,0333,4444,0333,0333

我用sed命令,但似乎我需要编辑一个文件,不能直接在我的代码。

我可以使用什么命令来格式化字符串?我是否正确使用该功能?我有我的变量的可见性吗?你知道更好的方法来实现我的目标吗?

在此先感谢!

回答

1

假设你只是想离开垫用零的数字,这可以在一个单一的命令来完成:

$ printf '%04d\n' "${ADDR[@]}" 
0333 
4444 
0333 
0333 
4444 
0333 
0333 

这里的阵列中的每个数字被传递给printf作为单独的参数 - 它照顾你的格式。

当然,这是否合适取决于你的计划如何使用这些数字。

另外,return仅用于指示例程是否成功。因此,它仅支持从0255的值。要从函数或命令输出某些内容,请使用标准输出/错误。

+0

这....只是...真棒谢谢 –

相关问题