lee*_*oon 3 macos bash grep text-processing sed
我有一个 .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>
Run Code Online (Sandbox Code Playgroud)
我要替换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>
Run Code Online (Sandbox Code Playgroud)
我试过这个:
cat foo.txt | grep "^.[\]{64} /Volumes/Documents - Part 1/" | sed " /Volumes/Documents - Part 1 BU"`
Run Code Online (Sandbox Code Playgroud)
但它没有用。我怎样才能解决这个问题?
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
Run Code Online (Sandbox Code Playgroud)
解决方案二: awk解决方案。
awk '{sub("Documents - Part 1","Documents - Part 1 BU")} 1' Input_file
Run Code Online (Sandbox Code Playgroud)
注意:sed -i如果您想将输出保存到 Input_file 本身并附> temp_file && mv temp_file Input_file加到第二个解决方案以执行相同操作,请使用上述代码中的选项。
| 归档时间: |
|
| 查看次数: |
534 次 |
| 最近记录: |