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
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.
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.
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.
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
You can append the text to $0
in awk if it matches the condition:
awk '/^all:/ {$0=$0" anotherthing"} 1' file
/patt/ {...}
if the line matches the pattern given by patt
, then perform the actions described within {}
./^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.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With