Add to the end of the line containing the template - with sed or awk

Here is an example file

somestuff... all: thing otherthing some other stuff 

What I want to do is add to the line starting with all: as follows:

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

Maybe I can do this with sed, but I'm not very good at sed, so can anyone help with it?

+62
bash awk sed
Mar 06 2018-12-12T00:
source share
5 answers

It works for me

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

The first part is a search pattern, and the second part is a regular lookup using $ to end the line.

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

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

Or you can redirect it to another file

 sed '/^all:/ s/$/ anotherthing/' file > output 
+117
Mar 06 '12 at 21:00
source share

This should work for you.

 sed -e 's_^all: .*_& anotherthing_' 

Using the s (substitute) command, you can search for a string that matches the regular expression. In the above command, & stands for string match.

+5
Mar 06 '12 at 21:00
source share

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

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

Explanation

  • /patt/ {...} if the string matches the pattern specified by patt , then follow the steps in {} .
  • In this case: /^all:/ {$0=$0" anotherthing"} , if the line starts (represented by ^) with all: then add anotherthing to the line.
  • 1 as a true condition, triggers the default action awk : prints the current line ( print $0 ). This will always happen, so it will either print the original line or the changed one.

Test

For this input, it returns:

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

Note that you can also provide text to add to the variable:

 $ awk -v mytext=" EXTRA TEXT" '/^all:/ {$0=$0mytext} 1' file somestuff... all: thing otherthing EXTRA TEXT some other stuff 
+3
Jan 25 '15 at 16:47
source share

Solution with awk:

 awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file 

Simple: if the line starts with all , print the line plus "anotherthing", otherwise print only the line.

+2
Mar 06 2018-12-21T00:
source share

In bash:

 while read -r line ; do [[ $line == all:* ]] && line+=" anotherthing" echo "$line" done < filename 
+1
Mar 06 2018-12-21T00:
source share



All Articles