python相当于sed

use*_*716 14 python

有没有办法,没有双循环来完成以下sed命令的作用

输入:

Time
Banana
spinach
turkey
Run Code Online (Sandbox Code Playgroud)

sed -i "/Banana/ s/$/Toothpaste/" file

输出:

Time
BananaToothpaste
spinach
turkey
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的是一份双重清单,需要很长时间才能完成.

列表a有一堆数字列表b有一堆相同的数字,但顺序不同

对于A中的每个条目,我想在B中找到具有相同数字的行,并在其末尾添加值C.

希望这是有道理的,即使我的例子没有.

我在Bash中做了以下操作但它工作得很慢但是速度很慢......

for line in $(cat DATSRCLN.txt.utf8); do
        srch=$(echo $line | awk -F'^' '{print $1}');
        rep=$(echo $line | awk -F'^' '{print $2}');
        sed -i "/$(echo $srch)/ s/$/^$(echo $rep)/" tmp.1;
done
Run Code Online (Sandbox Code Playgroud)

谢谢!

hel*_*ker 13

使用re.sub():

newstring = re.sub('(Banana)', r'\1Toothpaste', oldstring)
Run Code Online (Sandbox Code Playgroud)

这将捕获一个组(在第一个括号之间),并将其替换为ITSELF(\number部分),后跟所需的后缀.需要使用r''(原始字符串)以便正确解释转义.


Oz1*_*123 10

比赛的后来者,这是我在Python中使用sed的实现:

import re
import shutil
from tempfile import mkstemp


def sed(pattern, replace, source, dest=None, count=0):
    """Reads a source file and writes the destination file.

    In each line, replaces pattern with replace.

    Args:
        pattern (str): pattern to match (can be re.pattern)
        replace (str): replacement str
        source  (str): input filename
        count (int): number of occurrences to replace
        dest (str):   destination filename, if not given, source will be over written.        
    """

    fin = open(source, 'r')
    num_replaced = count

    if dest:
        fout = open(dest, 'w')
    else:
        fd, name = mkstemp()
        fout = open(name, 'w')

    for line in fin:
        out = re.sub(pattern, replace, line)
        fout.write(out)

        if out != line:
            num_replaced += 1
        if count and num_replaced > count:
            break
    try:
        fout.writelines(fin.readlines())
    except Exception as E:
        raise E

    fin.close()
    fout.close()

    if not dest:
        shutil.move(name, source) 
Run Code Online (Sandbox Code Playgroud)

例子:

sed('foo', 'bar', "foo.txt") 
Run Code Online (Sandbox Code Playgroud)

将在foo.txt中用'bar'替换所有'foo'

sed('foo', 'bar', "foo.txt", "foo.updated.txt")
Run Code Online (Sandbox Code Playgroud)

将'foo.txt'中的'bar'替换为'foo'并将结果保存在"foo.updated.txt"中.

sed('foo', 'bar', "foo.txt", count=1)
Run Code Online (Sandbox Code Playgroud)

将仅使用'bar'替换第一次出现的'foo',并将结果保存在原始文件'foo.txt'中


M. *_*del 5

If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed

wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py
Run Code Online (Sandbox Code Playgroud)

Place the module file into your Python3 modules path, then:

import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)
Run Code Online (Sandbox Code Playgroud)


shr*_*use 5

实际上,您可以从 python 调用 sed。有很多方法可以做到这一点,但我喜欢使用 sh 模块。(yum -y 安装 python-sh)

我的示例程序的输出如下。

[me@localhost sh]$ cat input 
Time
Banana
spinich
turkey
[me@localhost sh]$ python test_sh.py 
[me@localhost sh]$ cat input 
Time
Toothpaste
spinich
turkey
[me@localhost sh]$ 
Run Code Online (Sandbox Code Playgroud)

这是test_sh.py

import sh

sh.sed('-i', 's/Banana/Toothpaste/', 'input')
Run Code Online (Sandbox Code Playgroud)

这可能只能在 LINUX 下工作。