与sed等价的python

2024-04-18 07:58:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法,不使用双循环来完成下面的sed命令

输入:

Time
Banana
spinach
turkey

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

输出:

Time
BananaToothpaste
spinach
turkey

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

名单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

谢谢!


Tags: 方法命令echotimeline数字sedbanana
3条回答

如果您使用Python3,以下模块将帮助您: https://github.com/mahmoudadel2/pysed

wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py

将模块文件放入Python3模块路径,然后:

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

作为比赛的后起之秀,下面是我在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) 

示例:

sed('foo', 'bar', "foo.txt") 

将foo.txt中的所有“foo”替换为“bar”

sed('foo', 'bar', "foo.txt", "foo.updated.txt")

将所有“foo”替换为“foo.txt”中的“bar”,并将结果保存为“foo.updated.txt”。

sed('foo', 'bar', "foo.txt", count=1)

将只将“foo”的第一个匹配项替换为“bar”,并将结果保存到原始文件“foo.txt”

使用re.sub()

newstring = re.sub('(Banana)', r'\1Toothpaste', oldstring)

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

相关问题 更多 >