Do something for lines that do or do not END with a certain pattern in Linux bash

Home > Search
  by

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments