Squoggle
Mac's tech blog
Tag Archives: sed
Sed
Posted by on October 29, 2019
Down & Dirty Notes on SED
Replace a word with another word:
To replace all instances of a certain word in a file with another word:
$ sed 's/[oldword]/[newword]/' file
This will not modify the original file but output to the screen
Strip the last letter of a list of words:
If you have a file with a bunch of words that all end in the same letter, something like this:
austin1a denver1a dallas1a phoenix1a
and you want to strip the last letter off of each word you can do it with something like this:
$ sed 's/\(.*\)./\1/' file
Output is to screen.
Add a letter to the end of a list of words:
Lets say you want to add a letter to that list of words. You can do that like this:
$ sed 's/$/b/'file
This will add a letter b to the end of each word in the list.
Replace the last letter of word:
You can combine the above two commands and if you want to change all the of the a to letter b then you can do that like this:
$ sed 's/\(.*\)./\1/' file | sed 's/$/b/'
The first part of this command strips the last letter of each word. Then the second part of the command adds the letter b to the end of each word.
Add a trailing \
Many times you want to run a script against a list of servers or something. You can create a list with a space slash \ after each word in the file:
$ sed 's/$/ \\/' file
The results will look something like this:
austin1a \ denver1a \ dallas1a \ phoenix1a \
Insert text at the beginning of a word:
If you want to insert the word router at the beginning of each word you could do something like this:
$ sed 's/^/router/' file
Insert text at the end of a word:
Same as above but at the end of the word:
$ sed 's/$/router/' file
Convert commas to newline:
Lets say you have CSV list in a file that looks something like this:
austin1a,denver1a,dallas1a,phoenix1a
and you want to convert those commas into newline. You can do something like this:
$ sed -e $'s/,/\\\n/g' file
Sometimes that list will have a space after the comma like this:
austin1a, denver1a, dallas1a, phoenix1a
You can modify the command slightly like this:
$ sed -e $'s/, /\\\n/g' file
Convert TABs (White space) to Commas:
Lets say you have a TAB separated file and you want to convert it to a CSV file. An example would be something like this:
austin1a.example.com. 300 IN A 10.10.20.10 denver1a.example.com. 300 IN A 10.10.30.10 dallas1a.example.com. 300 IN A 10.10.40.10 phoenix1a.example.com. 300 IN A 10.10.50.10
This command will convert any white space to a comma:
$ sed 's/[[:space:]]\+/,/g' file
Convert multiple spaces to single space:
Or if you simply want to convert multiple spaces to a single space you can do like this:
$ sed 's/[[:space:]]\+/ /g' file
More to come…
Recent Comments