I want to append something at the end of a certain line(have some given character). For example, the text is:
Line1: I just want to make clear of the problem
Line2: Thanks to all who look into my problem
Line3: How to solve the problem?
Line4: Thanks to all.
Then I want to add "Please help me" at the end of
Line2: Thanks to all who look into my problem
And "Line2"
is the key word. (that is I have to append something by grep this line by key word).
So the text after the script should be:
Line1: I just want to make clear of the problem
Line2: Thanks to all who look into my problem Please help me
Line3: How to solve the problem?
Line4: Thanks to all.
I know sed
can append something to certain line but, if I use sed '/Line2/a\Please help me'
, it will insert a new line after the line. That is not what I want. I want it to append to the current line.
Could anybody help me with this?
Thanks a lot!
I'd probably go for John's
sed
solution but, since you asked aboutawk
as well:This outputs:
An explanation as to how it works may be helpful. Think of the
awk
script as follows with conditions on the left and commands on the right:These two
awk
clauses are executed for every single line processed.If the line matches the regular expression
^Line2:
(meaning "Line2:" at the start of the line), you change$0
by appending your desired string ($0
is the entire line as read intoawk
).If the line matches the empty condition (all lines will match this),
print
is executed. This outputs the current line$0
.So you can see it's just a simple program which modifies the line where necessary and outputs the line, modified or not.
In addition, you may want to use
/^Line2:/
as the key even for ased
solution so you don't pick upLine2
in the middle of the text orLine20
throughLine29
,Line200
throughLine299
and so on:Shell scripting