代码之家  ›  专栏  ›  技术社区  ›  leetbacoon

替换txt文件中每一行上匹配文本的第一个实例

  •  3
  • leetbacoon  · 技术社区  · 6 年前

    我有一个。txt文件,我想替换每行上第一个匹配字符串。

    例如,下面是foo的内部内容。txt文件:

    838dbc65cd79e16cf09f90abb928e3f3d0ea2d775cf8edc8acaabde6d393bc76  /Volumes/Documents - Part 1/legos.png
    415ccf1e05fb5985d2f719deabec7bb5d22aeaac7b82cca885010b12d483d997  /Volumes/Documents - Part 1/folder/Volumes/Documents - Part 1/another folder/Volumes/Documents - Part 1 BU/fedora linux.7z
    f3d0ea2d775cf8edc1ddbd76e2562d3e4a2e281fe2aeb1333ef99536d1a180ee  /Volumes/Documents - Part 1/manuals/dryer.pdf
    \ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  /Volumes/Documents - Part 1/Test Hash Folder/#;."'&,\\{2}:`!*?$(){}[]<>|-=+% [meowzers] (1)~^^.$[E-frLOL[MAY[]{}()?<NUL>
    \9c993445f7f6216b4fc7d35aef47afa16f4f831f2510b7fddd1e42c4cafb518c  /Volumes/Documents - Part 1/Test Hash Folder/#;."'&,\\:`!CAT      MEOW!!![hey]{15}(hello)@$%&^*(#@@*?$(){}[]<>|-=+% ~^^.$[E-frLOL[MAY[]{}()?<NUL>
    

    我想替换 Documents - Part 1 具有 Documents - Part 1 BU ,则, 但是 每行上只出现第一次。

    所以,最终看起来是这样的:

    838dbc65cd79e16cf09f90abb928e3f3d0ea2d775cf8edc8acaabde6d393bc76  /Volumes/Documents - Part 1 BU/legos.png
    415ccf1e05fb5985d2f719deabec7bb5d22aeaac7b82cca885010b12d483d997  /Volumes/Documents - Part 1 BU/folder/Volumes/Documents - Part 1/another folder/Volumes/Documents - Part 1 BU/fedora linux.7z
    f3d0ea2d775cf8edc1ddbd76e2562d3e4a2e281fe2aeb1333ef99536d1a180ee  /Volumes/Documents - Part 1 BU/manuals/dryer.pdf
    \ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  /Volumes/Documents - Part 1 BU/Test Hash Folder/#;."'&,\\{2}:`!*?$(){}[]<>|-=+% [meowzers] (1)~^^.$[E-frLOL[MAY[]{}()?<NUL>
    \9c993445f7f6216b4fc7d35aef47afa16f4f831f2510b7fddd1e42c4cafb518c  /Volumes/Documents - Part 1 BU/Test Hash Folder/#;."'&,\\:`!CAT      MEOW!!![hey]{15}(hello)@$%&^*(#@@*?$(){}[]<>|-=+% ~^^.$[E-frLOL[MAY[]{}()?<NUL>
    

    我试过这个:

    cat foo.txt | grep "^.[\]{64}  /Volumes/Documents - Part 1/" | sed "  /Volumes/Documents - Part 1 BU"`
    

    但它没有起作用。我怎样才能解决这个问题?

    Mac OS X Yosemite,bash 3.2.57(1)-发布,grep(BSD grep)2.5.1-FreeBSD

    1 回复  |  直到 6 年前
        1
  •  5
  •   RavinderSingh13    6 年前

    解决方案1: 下列的 sed 可能对你也有帮助。

    sed 's/Documents - Part 1/Documents - Part 1 BU/'   Input_file
    

    解决方案2: awk 解决方案

    awk '{sub("Documents - Part 1","Documents - Part 1 BU")} 1'   Input_file
    

    注: 使用 sed -i 如果要将输出保存到Input\u文件本身并附加 > temp_file && mv temp_file Input_file 到第二个解决方案进行相同操作。