Do you know Sed? If you ask ‘who is he’, then this little article if for you. Here goes…
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | # 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 pineapple EOM ) # 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 hostname =lax-linux06 sed -i '/127.0.1.1/ c\127.0.1.1 ' "$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 file = /etc/grub .d /30_os-prober lastMatchLineNumber=$( grep -n 'adjust_timeout' "$file" | tail -1| cut -f1 -d ':' ) sed -e "$lastMatchLineNumber s/^#*/#/" -i $ file # Add a line after last matching line file = /etc/grub .d /30_os-prober sed -e "$(grep -n 'adjust_timeout' " $ file " |tail -1|cut -f1 -d':')a NEWLINECONTENTHERE" -i $ file |
Categories: