【问题标题】:Increment all numbers in a file增加文件中的所有数字
【发布时间】:2014-07-16 15:12:43
【问题描述】:

我有一个看起来像这样的文件:

(890 1782 0)
(8 9 56)(5 28 987)

我想将每个数字加一:

(891 1783 1)
(9 10 57)(6 29 988)

我确信一定有一种简单的方法可以做到这一点,但我想不通。对任何语言都很满意(bash/awk/perl/python)

【问题讨论】:

    标签: python regex bash scripting


    【解决方案1】:

    您可以使用\d+ 正则表达式查找所有数字,使用re.sub() 并将函数作为repl 参数传递给。原地修改文件,可以使用fileinput:

    import fileinput
    import re
    
    pattern = re.compile('\d+')
    for line in fileinput.input('input.txt', inplace=True):
        if line:
            print pattern.sub(lambda m: str(int(m.group(0)) + 1), line)
    

    示例(使用字符串而不是文件):

    >>> import re
    >>> s = "(891 1783 1)"
    >>> pattern = re.compile('\d+')
    >>> pattern.sub(lambda m: str(int(m.group(0)) + 1), s)
    '(892 1784 2)' 
    

    【讨论】:

    • 不过,这会为每一行添加一个额外的换行符。
    【解决方案2】:

    我的解决方案:

    numbers=$(egrep -o "[0-9]+" input.txt | xargs printf "%d + 1\n"  | bc)
    printf "$(cat input.txt  | sed -r 's/[0-9]+/%d/g')\n" $numbers
    

    【讨论】:

      猜你喜欢
      • 2013-10-16
      • 2021-06-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多