BASH用其他字符替换char来填充单词

时间:2012-12-26 19:55:31

标签: bash sed awk

我需要根据需要将所选字符替换为另一个字符的副本,以填充确定的空格(精确的12个字符)。

示例,将char'1'替换为零或多个char'0':

ABC1           =>  ABC000000000
ABC1JKL        =>  ABC000000JKL
1JKL           =>  000000000JKL
1000           =>  000000000000
ABCDEFGHIJKL1  =>  ABCDEFGHIJKL
1ABCDEFGHIJKL  =>  ABCDEFGHIJKL
ABCDEFGHIJKL   =>  ABCDEFGHIJKL
1EFG1          =>  undefined (do not bother with this case)
EFG            =>  undefined (do not bother with this case)

3 个答案:

答案 0 :(得分:1)

使用bash的参数扩展:

#! /bin/bash
inputs=(ABC1             
    ABC1JKL          
    1JKL             
    1000             
    ABCDEFGHIJKL1    
    1ABCDEFGHIJKL    
    ABCDEFGHIJKL     
)

outputs=(ABC000000000
    ABC000000JKL
    000000000JKL
    000000000000
    ABCDEFGHIJKL
    ABCDEFGHIJKL
    ABCDEFGHIJKL
)

for ((i=0; i<${#inputs[@]}; i++)) ; do
    x=${inputs[i]}
    while [[ ${x:12} ]] ; do               # Shorten if too long
        x=${x/1}
    done
    while [[ ${x:11} == '' ]] ; do         # Insert 1's if too short
        x=${x/1/11}
    done
    x=${x//1/0}
    [[ $x == ${outputs[i]} ]] || echo Different $x
done

答案 1 :(得分:1)

awk中的解决方案:

{
  temp = $1
  gsub (/[^1]/, "", temp)
  if (length(temp) == 1) {
    l = 12 - (length ($1) - 1)
    if (l > 0) {
      t = "000000000000"
      sub (/1/, substr (t,0,l), $1)
    }
  }
  print $1
}

bash / sed中的解决方案:

#!/bin/bash

while read n; do
  temp=$(echo $n | sed 's/[^1]//g')
  if [[ ${#temp} == 1 ]]; then
    l=$(( 12 - $(( ${#n} - 1)) ))
    if [[ $l > 0 ]]; then
      t=000000000000
      n=$(echo $n | sed "s/1/${t:0:$l}/")
    fi
  fi
  echo $n
done

答案 2 :(得分:1)

由于每个人都在给自己的个人答案,这是我自己的酿造( 100%纯粹的bash ),可能是代码高尔夫的好候选人(也可能是效率最高的人之一)循环,没有管道,只有一个子shell(见帖子的末尾去除它)):

$ string="ABC1"
$ echo "${string/1/$(printf "%.$((13-${#string}))d" 0)}"
ABC000000000

我赢了吗?

如果您无法相信这一个班轮工作,请转到:

$ while read string; do printf "%s%$((13-${#string}))s => %s\n" "$string" '' "${string/1/$(printf "%.$((13-${#string}))d" 0)}"; done < <(printf "%s\n" ABC1 ABC000000000 ABC1JKL 1JKL 1000 ABCDEFGHIJKL1 1ABCDEFGHIJKL ABCDEFGHIJKL 1EFG1 EFG)
ABC1          => ABC000000000
ABC000000000  => ABC000000000
ABC1JKL       => ABC000000JKL
1JKL          => 000000000JKL
1000          => 000000000000
ABCDEFGHIJKL1 => ABCDEFGHIJKL
1ABCDEFGHIJKL => ABCDEFGHIJKL
ABCDEFGHIJKL  => ABCDEFGHIJKL
1EFG1         => 00000000EFG1
EFG           => EFG

想要摆脱这种方法中的子shell?很简单,但你需要一个辅助变量:

$ string="ABC1"
$ printf -v aux "%.$((13-${#string}))d" 0
$ echo "${string/1/$aux}"
ABC000000000