Reputation: 1249
I have a .txt file and I want to replace the first occurrence of a matching string on every line.
So, for example, here's what's inside 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>
I want to replace Documents - Part 1
with Documents - Part 1 BU
, but only the first occurrence on every line.
So, it would look like this in the end:
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>
I tried this:
cat foo.txt | grep "^.[\]{64} /Volumes/Documents - Part 1/" | sed " /Volumes/Documents - Part 1 BU"`
but it didn't work. How can I fix this?
Mac OS X Yosemite, bash 3.2.57(1)-release, grep (BSD grep) 2.5.1-FreeBSD
Upvotes: 3
Views: 684
Reputation: 133630
Solution 1st: Following sed
may help you on same.
sed 's/Documents - Part 1/Documents - Part 1 BU/' Input_file
Solution 2nd: awk
solution.
awk '{sub("Documents - Part 1","Documents - Part 1 BU")} 1' Input_file
NOTE: Use sed -i
option in above code in case you want to save output into Input_file itself and append > temp_file && mv temp_file Input_file
to 2nd solution for doing the same.
Upvotes: 5