• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: [OT] Shell scripting (2)
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [OT] Shell scripting (2)


  • Subject: Re: [OT] Shell scripting (2)
  • From: Christopher Nebel <email@hidden>
  • Date: Sun, 28 Dec 2003 11:15:06 -0800

On Dec 27, 2003, at 5:36 PM, Marc K. Myers wrote:

Could someone point me in the right direction as to how to do a find and replace on files in the Unix shell? What I'm doing now is reading the file into a variable, using a TID handler to find and replace, and writing the contents back to the file. Since this is such a common need there is probably a much easier way to do it via shell scripting.

There are a variety of tools to do search-and-replace type things: tr does individual characters, sed does strings (and a few other things), awk is good at handling columnar text, and of course, perl does everything.

Because of how file streams in Unix work, most tools don't let you mangle a file in-place -- you have to read from one file and write to another. Sometimes this is exactly what you want, but otherwise it's a bit of a pain. Perl has the added bonus of an option (-i) that will do in-place mangling for you. For example:

perl -i -p -e 's/findstring/replacestring/' thefile

Or, in AppleScript terms:

set thefile to POSIX path of (choose file)
set f to "find"
set r to "replace"
do shell script "perl -i -p -e 's/" & f & "/" & r "/' " & quoted form of thefile

Or something like that. Getting the quoting of the substitution command right for all possible input strings is left as an exercise for the reader.


--Chris Nebel
AppleScript Engineering
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.

References: 
 >[OT] Shell scripting (2) (From: "Marc K. Myers" <email@hidden>)

  • Prev by Date: Re: [OT] Shell scripting (2)
  • Next by Date: Odd behavior with Satimage's "backup" command
  • Previous by thread: [OT] Shell scripting (2)
  • Next by thread: Re: [OT] Shell scripting (2)
  • Index(es):
    • Date
    • Thread