Linux: substitute text with sed
sed is one of the best tools to replace text in files! it's very easy and super versatile, lets see some simple examples!
sed is one of the best tools to replace text in files! it's very easy and super versatile, lets see some simple examples!
What is sed
sed (“stream editor”) is a Unix utility that parses and transforms text, using a simple, compact programming language. sed was developed from 1973 to 1974 by Lee E. McMahon of Bell Labs,[1] and is available today for most operating systems.[2] sed was based on the scripting features of the interactive editor ed (“editor”, 1971) and the earlier qed (“quick editor”, 1965–66). sed was one of the earliest tools to support regular expressions, and remains in use for text processing, most notably with the substitution command. Popular alternative tools for plaintext string manipulation and “stream editing” include AWK and Perl.
How to substitute text using sed
The following example shows a typical, and the most common, use of sed: substitution. This usage was indeed the original motivation for sed.$ echo "Hello World" | sed 's/Hello/Good bye/'
Good bye World
If the Hello word occurs more than one in our input it will replace Hello only once.$ echo "Hello World Hello Friends" | sed 's/Hello/Good bye/'
Good bye World Hello Friends
To substitute each Hello occurrence, we need to use the “g” option.$ echo "Hello World Hello Friends" | sed 's/Hello/Good bye/g'
Good bye World Good bye Friends
If the input comes from a file and not stdin the following syntax must be used.sed 's/text_to_search/text_to_substitute/g' inputFileName > outputFileName
Changes can be made in place using the -i parameter.
sed -i 's/I hope you found this article easy to follow and make your life easier using sed!