How to use the sed command: Difference between revisions
No edit summary |
|||
Line 3: | Line 3: | ||
Usage: | Usage: | ||
sed [ | sed [OPTIONS] [input file] | ||
cat <textfile> | sed [OPTIONS] | |||
===Substitution=== | ===Substitution=== |
Revision as of 17:43, 19 October 2018
Introduction
sed (stream editor) allows you to manipulate text files or text inputs that are piped to it. You can use it to substitute certain characters, words, or numbers for different ones, selectively delete them, or choose to print relevant portions of a text.
Usage:
sed [OPTIONS] [input file] cat <textfile> | sed [OPTIONS]
Substitution
Use the command 'sed s/' to initiate a substitution command. After the initial 's/', you must provide it the word you would like to change, then delimit that selection with another slash, '/'. Afterwards, you will then provide another word or number you would like to change the previous entry, then again end your selection with a '/'.
Usage:
sed 's/[text_to_select]/[text_for_replacement]/'
You can use sed to correct small character mistakes:
# substitutes the letter 'B' for 'F'. Ensure your substitution command ends with a '/' [root@he ~]# echo UCSB | sed 's/B/F/' UCSF
And also use sed to replace a word with a phrase
-sh-4.1$ echo "I am fat but I will be skinny" I am fat but I will be skinny # now with a sed command to reflect yours truly's reality, substituting the word 'skinny' with a phrase 'even more fat' -sh-4.1$ echo I am fat but I will be skinny | sed 's/skinny/even more fat/' I am fat but I will be even more fat
Notice that we surround with argument to sed with apostrophes, '. This is the best practice when providing arguments to sed.
sed will only change the first instance of a segment of text. Notice how the following text has multiple instances of the same word but sed will only change the first instance.
-sh-4.1$ echo water water everywhere nor any drop to drink | sed 's/water/lemonade/' lemonade water everywhere nor any drop to drink
Examples
[root@he ~]# virsh list --all Id Name State ---------------------------------------------------- 1 chi running 2 gamma running 3 beta running [root@he ~]# virsh list --all | sed s/running/jogging/ 1 chi jogging 2 gamma jogging 3 beta jogging