Replacing string in file with MAC OSX

16,742

Solution 1

How it to do with sed in OS X.

I've created test file:

$ cat test.txt
tasdasdasd

asd
asd
as
d
as
d
ddddddd

ffdfdfdfdfdf

Calling sed ('' is necessarily parameter):

$ sed -i '' "s/as/replaced_ad/g" test.txt

Show output file:

$ cat test.txt
treplaced_addreplaced_addreplaced_add

replaced_add
replaced_add
replaced_ad
d
replaced_ad
d
ddddddd

ffdfdfdfdfdf

sed in OS X is slightly changes from GNU sed. Use man sed in OS X terminal to know how to use sed.

Solution 2

Weird. Replacing " with ' apparently worked.

sed -i '' "s/as/replaced_ad/g" test.txt

did nothing, whereas

sed -i '' 's/as/replaced_ad/g' test.txt

gave me what I needed. ?????

I thought there were no difference between single and double quotes on machos?????

Well, as long as I can go on with my work..... Thanks Yurij, again.

Share:
16,742

Related videos on Youtube

Christoffer Bugge Harder
Author by

Christoffer Bugge Harder

Updated on September 18, 2022

Comments

  • Christoffer Bugge Harder
    Christoffer Bugge Harder over 1 year

    I need to replace a string in a (large) file on a MacOSX 10.10. My file looks like this:

    Y16-TUL-SUB_ Y16-TUL-SUB_ Y16-TUL-SUB_ Y16-TUL-SUB_ Y16-TUL-SUB-
    Y16-TUL-SUB_ Y16-TUL-SUB_
    

    and I need to replace Y16_TUL_SUB_ with Y16-TUL-SUB-. File name could be test.txt.

    I have tried a lot of the different suggestions with sed, awk and python. E.g this:

    #!/usr/bin/env python import sys import os import tempfile
    
     tmp=tempfile.mkstemp()
    
     with open(sys.argv[1]) as fd1, open(tmp[1],'w') as fd2:
         for line in fd1:
             line = line.replace('Y16_TUL_SUB_','Y16-TUL-SUB-')
             fd2.write(line)
    
     os.rename(tmp[1],sys.argv[1])
    

    or sed supposedly for mac

    or find:

     find . -type f -name test.txt | xargs sed -i ""
     "s/Y16_TUL_SUB_/Y16-TUL-SUB-/g'
    

    or sed:

     sed -i -e "s/Y16_TUL_SUB_/Y16-TUL-SUB/g" test.txt
    

    or awk

     awk '{gsub(/Y16_TUL_SUB_/,"Y16-TUL-SUB")}' test.txt
    

    All these commands have run and returned empty output files, or not changed anything in the original files anyway.

    What am I doing wrong?

  • Christoffer Bugge Harder
    Christoffer Bugge Harder almost 5 years
    Hi Yurij, I appreciate your help, but unfortunately this does nothing for me. Once again, no changes in file. :( Output file is empty
  • Christoffer Bugge Harder
    Christoffer Bugge Harder almost 5 years
    When I copy-paste (or write myself) your EXACT command on the EXACT file you display, the output file I get is empty.
  • chill appreciator
    chill appreciator about 3 years
    This exact command worked for me on Catalina. But I have ohmyzsh, maybe it changes standard sed