Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to the end of lines containing a pattern with sed or awk?

Tags:

bash

sed

awk

Here is example file:

somestuff... all: thing otherthing some other stuff 

What I want to do is to add to the line that starts with all: like this:

somestuff... all: thing otherthing anotherthing some other stuff 
like image 868
yasar Avatar asked Mar 06 '12 20:03

yasar


People also ask

How do you insert a sed line after a pattern?

You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.

How do I put something at end of line in Linux?

Using a text editor, check for ^M (control-M, or carriage return) at the end of each line. You will need to remove them first, then append the additional text at the end of the line. Save this answer.

How do I add a string at the end of a line in Unix?

There are many ways: sed : replace $ (end of line) with the given text. awk : print the line plus the given text. Finally, in pure bash : read line by line and print it together with the given text.


2 Answers

This works for me

sed '/^all:/ s/$/ anotherthing/' file 

The first part is a pattern to find and the second part is an ordinary sed's substitution using $ for the end of a line.

If you want to change the file during the process, use -i option

sed -i '/^all:/ s/$/ anotherthing/' file 

Or you can redirect it to another file

sed '/^all:/ s/$/ anotherthing/' file > output 
like image 58
user219882 Avatar answered Oct 31 '22 04:10

user219882


You can append the text to $0 in awk if it matches the condition:

awk '/^all:/ {$0=$0" anotherthing"} 1' file 

Explanation

  • /patt/ {...} if the line matches the pattern given by patt, then perform the actions described within {}.
  • In this case: /^all:/ {$0=$0" anotherthing"} if the line starts (represented by ^) with all:, then append anotherthing to the line.
  • 1 as a true condition, triggers the default action of awk: print the current line (print $0). This will happen always, so it will either print the original line or the modified one.

Test

For your given input it returns:

somestuff... all: thing otherthing anotherthing some other stuff 

Note you could also provide the text to append in a variable:

$ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file somestuff... all: thing otherthing EXTRA TEXT some other stuff 
like image 30
fedorqui 'SO stop harming' Avatar answered Oct 31 '22 04:10

fedorqui 'SO stop harming'