File editing with SED
In addition to editors like emacs, you can also edit files directly from the terminal using sed, the built-in stream editor. You can use it to make substitutions or deletions in a file with commands such as:
sed 's/oldword/newword/g' filename
which substitutes “newword” for “oldword”. The “g” makes the substitution global (all instances on that line). Without the g, it will only change the first match on that line.
Other sed commands:
sed 's/word/d' filename
This deletes the whole line, not just the word. To delete just the word:
sed 's/word//' filename
The examples given will print out the changes to the terminal. If you want to print the changes to a file instead type:
sed 's/oldword/newword/' filename > newfilename where > directs the output into a file called newfilename
To link more than one command together use &&. For example:
sed 's/oldword/newword/' filename > newfilename && emacs newfilename
sed ‘s/string1/string2/g’ | Replace string1 with string2 | |
sed ‘s/\(.*\)1/\12/g’ | Modify anystring1 to anystring2 | |
sed ‘/ *#/d; /^ *$/d’ | Remove comments and blank lines | |
sed ‘:a; /\\$/N; s/\\\n//; ta’ | Concatenate lines with trailing \ | |
sed ‘s/[ \t]*$//’ | Remove trailing spaces from lines | |
sed ‘s/\([\\`\\”$\\\\]\)/\\\1/g’ | Escape shell metacharacters active within double quotes | |
• | seq 10 | sed “s/^/ /; s/ *\(.\{7,\}\)/\1/” | Right align numbers |
sed -n ‘1000p;1000q‘ | Print 1000th line | |
sed -n ‘10,20p;20q‘ | Print lines 10 to 20 | |
sed -n ‘s/.*<title>\(.*\)<\/title>.*/\1/ip;T;q‘ | Extract title from HTML web page | |
sort -t. -k1,1n -k2,2n -k3,3n -k4,4n | Sort IPV4 ip addresses | |
• | echo ‘Test’ | tr ‘[:lower:]’ ‘[:upper:]’ | Case conversion |
• | tr -dc ‘[:print:]’ < /dev/urandom | Filter non printable characters |
• | history | wc -l | Count lines |