If you leave off the /g (with s/few/asd/, there always needs to be three slashes no matter what) and few appears twice on the same line, only the first few is changed to asd: g stands for "global", meaning to do this for the whole line. S/ is used to substitute the found expression few with asd: Sed is the stream editor, in that you can use | (pipe) to send standard streams (STDIN and STDOUT specifically) through sed and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition but can edit files directly, too, using the -i parameter mentioned below.Ĭonsider the following: sed -i -e 's/few/asd/g' hello.txt Python can also have regular expressions, in particular, there's re module, which has re.sub() function, which can be used for more advanced replacements. myscript.py is in your current working directory and for the first way, ensure it is set executable with chmod +x. The exact command to run python script with command-line argument would be $. This script is to be called with input.txt as command-line argument. With open(sys.argv) as fd1, open(tmp,'w') as fd2: For instance, here's a simple one: #!/usr/bin/env python With Python, however, you also need to output to new file, which you can also do from within the script itself. Simple way to read file and replace string in it would be as so: python -c "import sys lines=() print lines.replace('blue','azure')" < input.txt It has a lot of functions for working with strings, among which is replace(), so if you have variable like var="Hello World", you could do var.replace("Hello","Good Morning") This language is very versatile and is also used in a wide variety of applications. Simple substitution can be done as so: perl -pe 's/blue/azure/' input.txt It borrowed a lot of concepts/features from other languages such as C,sed,awk, and others. Perl is another tool which is often used for text processing, but it's a general purpose language, and is used in networking, system administration, desktop apps, and many other places. What's good about this tool is that it has in-place editing, which you can enable with -i flag. It also uses regular expressions, but for simple substitutions it's sufficient to do: sed 's/blue/azure/' input.txt This is an input.txt and this doesn't rhymeīash isn't really meant for text processing, but simple substitutions can be done via parameter expansion, in particular here we can use simple structure $" The file contents: roses are red, violets are blue In this answer I am using simple input.txt file, which you can use to test all examples provided here. Depending on the complexity of what one tries to achieve with string replacement, and depending on tools with which user is familiar, some methods may be preferred more than others.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |