Add String at the end of line containing pattern

Add String at the end of line containing pattern

I need to add a STRING / VALUE at the end of the line containing a certain REGEX / Pattern in a file.

So let’s take the following file content of some_file.txt for instance.

Important line
Critical very important line
Critical All hands on the deck
Important line, but can be ignored
Warning content

So in the above file, I need to add string “HIGH ALERT” at the end of the lines beginning with “Critical”.

The best bet we have in this case is sed or awk.

Add String at the end of line containing pattern using SED

Let’s try to achieve this using sed.

The following is the syntax to be used.

sed ‘/SEARCH_REGEX/ s/$/ NEW_STRING/’

So to achieve the results in our case, we will use the following command.

[[email protected] ~]# sed ‘/^Critical/ s/$/ HIGH ALERT/’ some_file.txt

Output:

Important line
Critical very important line HIGH ALERT
Critical All hands on the deck HIGH ALERT
Important line, but can be ignored
Warning content

You can always use the -i flag for sed to modify the file directly.

Add String at the end of line containing pattern using AWK

Let’s achieve the same thing using awk.

The syntax to be used will be.

awk ‘{if ($N ~ /SEARCH_STRING/) print $0, “NEW_STRING”; else print $0}’

Where, $N will be field to be used to match the SEARCH_STRING / Pattern.

So in our case we will use $1, since the pattern we are tring to find is at the beginning of the line.

[[email protected] ~]# awk ‘{if ($1 ~ /^Critical/) print $0, “HIGH ALERT”; else print $0}’ some_file.txt

Output:

Important line
Critical very important line HIGH ALERT
Critical All hands on the deck HIGH ALERT
Important line, but can be ignored
Warning content

Add String at the end of line containing pattern

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.