如何使用sed或awk

时间:2016-03-10 11:15:43

标签: bash awk sed

我想在第一行中包含word1并以word2结尾的段落的每一行的开头删除一个模式,例如,如果我有以下文件并且我想要替换--MW by nothing

--MW Word1 this is paragraph number 1 
--MW aaa
--MW bbb
--MW ccc
--MW word2

我想得到结果:

Word1 this is paragraph number 1 
aaa
bbb
ccc
word2

提前致谢

4 个答案:

答案 0 :(得分:2)

使用sed

sed '/Word1/,/word2/s/--MW //' file

使用awk

awk '/Word1/,/word2/{sub(/--MW /,a)}1' file

两者都作用于匹配短语之间的行和包括在每行上的替换。他们打印所有行。

答案 1 :(得分:1)

如果您的文字在myfile.txt,则可以尝试:

awk 'BEGIN{f=0}$2=="Word1"{f=1}{if (f==1) {$1="";print $0}else{print $0}}$2=="word2"{f=0}' myfile.txt

答案 2 :(得分:0)

如果您确定该模式将位于该行的开头,那么此命令可能有所帮助:

def main():
    output_file_loc = "overview.pdf"
    imgDoc = canvas.Canvas(output_file_loc)
    imgDoc.setPageSize(A4) # This is actually the default page size
    document_width, document_height = A4

    images = image_search()
    for image in images:
        # Open the image file to get image dimensions
        Image_file = Image.open(image)
        image_width, image_height = Image_file.size
        image_aspect = image_height / float(image_width)

        # Determine the dimensions of the image in the overview
        print_width = document_width
        print_height = document_width * image_aspect

        # Draw the image on the current page
        # Note: As reportlab uses bottom left as (0,0) we need to determine the start position by subtracting the
        #       dimensions of the image from those of the document
        imgDoc.drawImage(image, document_width - print_width, document_height - print_height, width=print_width,
                         height=print_height)

        # Inform Reportlab that we want a new page
        imgDoc.showPage()

    # Save the document
    imgDoc.save()

请测试并告诉我们这是否适合您。

答案 3 :(得分:0)

希望这能为你做到:

$ echo "--MW Word1 this is paragraph number 1" | cut -d ' ' -f 2-

将文本传递给cut命令并删除第一个标记,使用空格作为标记分隔符,同时保留其余标记,即从第二个到结尾。