r/dailyprogrammer • u/nottoobadguy • Feb 17 '12
[2/17/2012] Challenge #9 [intermediate]
Write a program that will take a string ("I LIEK CHOCOLATE MILK"), and allow the user to scan a text file for strings that match. after this, allow them to replaces all instances of the string with another ("I quite enjoy chocolate milk. hrmmm. yes.")
7
Upvotes
2
u/DLimited Feb 17 '12
D2.058. Second commandline argument takes the file to be opened; the string to search for and to replace with are both requested.
1
u/eruonna Feb 17 '12
bash + sed, takes the filename on the command line and the search and replace interactively:
1
u/[deleted] Feb 17 '12 edited Feb 17 '12
Perl. Lengthier than it should be, but oh well.
1
u/blisse Feb 17 '12
Python. Couldn't make it case insensitive :\
I'm pretty sure the while loop is redundant, but I haven't tested how str.replace() handles the case when the word isn't in the str.
1
u/whereisbill Feb 18 '12
JavaScript version because I'm procrastinating (requires a newish browser as it uses the FILE API). http://jsfiddle.net/NTNkf/2/
1
u/Crystal_Cuckoo Feb 18 '12
Simple one-liner in sed, last bit overwrites the file with the replacements while also displaying it on the standard output:
1
u/cooper6581 Feb 18 '12
Python. I wasn't sure what should be used to delimit the strings, so this is just line replacement. http://codepad.org/3Pq7uyj9
1
u/Should_I_say_this Jul 07 '12
Doesn't take into account whether the file has upper or lower case. It's easy to modify the below so that the entire file is read in lower case, and the search term is converted to lower case, but the issue with that is, it gets a bit more difficult recreating the original file, with capitalized letters where they originally were. Anyways this is good enough for a practice problem :)