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

Replace first instance of matching text on every line in a txt file

我有一个 .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>
c993445f7f6216b4fc7d35aef47afa16f4f831f2510b7fddd1e42c4cafb518c  /Volumes/Documents - Part 1/Test Hash Folder/#;."'&,\:`!CAT      MEOW!!![hey]{15}(hello)@$%&^*(#@@*?$(){}[]<>|-=+% ~^^.$[E-frLOL[MAY[]{}()?<NUL>

我想用 Documents - Part 1 BU 替换 Documents - Part 1 但是 只在每一行中出现第一次。

所以,最后看起来像这样:

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>
c993445f7f6216b4fc7d35aef47afa16f4f831f2510b7fddd1e42c4cafb518c  /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)-release, grep (BSD grep) 2.5.1-FreeBSD

解决方案一:关注sed可能对你有帮助。

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

方案二:awk方案

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

注意: 如果您想将输出保存到 Input_file,请在上面的代码中使用 sed -i 选项本身并将 > temp_file && mv temp_file Input_file 附加到第二个解决方案以执行相同的操作。