Bash (Scripting) - do something match does/doesn't end with pattern

by
Jeremy Canfield |
Updated: March 08 2020
| Bash (Scripting) articles
Append to end of line
The $ character is used to do something from the end of a line. For example, let's say you have string "Hello World". With the most basic use, sed with $ can be used to append test to the end of the string. In this example, "Testing" is appended to the end of "Hello World".
~]# echo "Hello World" | sed "s|$| Testing|"
Hello World Testing
Replace end of line
The $ character is often used to replace text at the end of a line. In this example, lines ending with the word "World" are replaced with the word "Earth".
~]# echo "Hello World" | sed "s|World$|Earth|"
Hello Earth
Remove lines that end with
The following sed statement can be used to remove lines that do end with the word World.
~]# sed '/World$/d' /path/to/file.txt
How are you
Likewise, the following sed statement can be used to remove lines that do not end end with the word World.
~]# sed '/World$/!d' /path/to/file.txt
Hello World
Did you find this article helpful?
If so, consider buying me a coffee over at