BASH: Basic SED Training

Do you know Sed? If you ask ‘who is he’, then this little article if for you. Here goes…

# Simple substitution, 1-time matching
echo "apple apple pen pineapple" | sed 's/apple/pen/'
# output: pen apple pen pineapple

# Simple substitution of @ with @@
sudo sed 's/@/@@/' -i /etc/rsyslog.d/vyatta-log.conf

# Substitute second occurence of a word
echo "apple pineapple pen apple" | sed 's/apple/pen/2'
# output: apple pinepen pen apple

# Substitute all occurences of a word
echo "apple pen apple pen apple" | sed 's/apple/pen/g' 
# output: pen pen pen pen pen

# Replacing from nth occurrence to all occurrences in a line
echo "apple apple pen pineapple apple" | sed 's/apple/pen/3g'
# output: apple apple pen pinepen pen

# Capitalize first letter of each word
echo "apple apple pen pineapple apple" | sed 's/\(\b[a-z]\)/\U\1/g'
# Output: Apple Apple Pen Pineapple Apple

# Creating variable named $song with multiple lines
song=$(cat <<- EOM
	apple apple apple pen
	pen apple aple pen
	pen pen pen apple

# Delete the last line of multi-string variable
echo "$song" | sed '$d'

# Delete the whole line matching a word within a text file
sed '/pineapple/d' textfile.txt

# Comment a line matching a word
sed '/^#/! {/MATCHWORD/ s/^/#/}' -i file.cfg

# Uncomment a line matching a word
sed -i '/<word>/s/^#//g' file.cfg

# Replace a line in file
sed -i '/ c\ '"$hostname"'' /etc/hosts

# Insert Line after [Service] to bypass memory checking - remember to escape special characters and to use option -i to update file in-line
sudo sed -i '/^\[Service\]*/a Environment=SYSTEMD_BYPASS_HIBERNATION_MEMORY_CHECK=1' /lib/systemd/system/systemd-logind.service

# Comment out last matching line
lastMatchLineNumber=$(grep -n 'adjust_timeout' "$file" |tail -1|cut -f1 -d':')
sed -e "$lastMatchLineNumber s/^#*/#/" -i $file

# Add a line after last matching line
sed -e "$(grep -n 'adjust_timeout' "$file" |tail -1|cut -f1 -d':')a NEWLINECONTENTHERE" -i $file
Posted on Categories Linux

Leave a Reply

Your email address will not be published. Required fields are marked *