Sed
Jump to navigation
Jump to search
Find and replace a line:
sed -i 's/foo/bar/g' FILENAME
Search for terms at the beginning of each line with or without whitespace:
sed 's/^foo *= *1/bar=0/'
Append a new line after a search result:
sed '/RESULT/ a NEWLINE'
String multiple commands together:
sed -e 's/^foo *= *1/#foo=1/; /#foo=1/ a bar=0'
Replace // with / easily:
sed 's_//_/_g'
Delete all lines with --:
cat FILENAME | sed '/--/d'
Replace the first space in a line with an @ symbol:
sed 's/ /@/'
Grab a single line from a log file:
sed -n '<number>{p;q}' <file>
So for line 46 in main.php:
sed -n '46{p;q}' main.php
Copy a range of lines to a new file:
1. Tail the log to get the date format:
tail /usr/local/apache/domlogs/example.com | head -n1
2. Use grep -n to get the line range:
grep -n "29/Jun/2012:14:15" /usr/local/apache/domlogs/example.com | head -n1 grep -n "29/Jun/2012:15:36" /usr/local/apache/domlogs/example.com | tail -n1
3. Use sed to copy those lines and everything in between to a new file:
sed -n '19081,26356p' /usr/local/apache/domlogs/example.com >> /root/newfile
Or just find the range of text you need if you don't know the line numbers:
sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' ssl.txt
Nix characters
Nix the last character of stout: Pipe into:
sed s/.$//
Nix the last 3 characters of a string:
sed "s/...$//"
Keep only the last 3 characters of a string:
sed "s/.*\(...$\)/\1/"
Nix lines from stdout:
Pipe your command into these: Nix the first line:
sed -n '1!p'
Nix the first three lines:
sed -n '1,3!p'
This lets you do an ls for a vertical list of files for a for loop, like so:
ls -l | sed -n '1,3!p' | rev | cut -d' ' -f1 | rev
For cPanel users from userdata dir:
ls -l /var/cpanel/userdata | sed -n '1,3!p' | rev | cut -d' ' -f1 | rev | cut -d '/' -f1 | grep -v nobody
Or you might want to nix the file extension too, to make backups:
for i in $(ls -1 | sed -n '1,2!p' | cut -d '.' -f1); do cp -a $i.png $i-old.png; done