How to append something at the end of a certain line of the text
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 about awk
as well:
$ echo '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.' | awk '/^Line2:/{$0=$0" Please help me"}{print}'
This outputs:
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.
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:
/^Line2:/ {$0=$0" Please help me"}
{print}
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 into awk
).
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 a sed
solution so you don't pick up Line2
in the middle of the text or Line20
through Line29
, Line200
through Line299
and so on:
sed '/^Line2:/s/$/ Please help me/'
sed '/Line2/ s/$/ Please help me/'
Shell scripting
while read -r line
do
case "$line" in
*Line2* ) line="$line Please help me";;
esac
echo "$line"
done <"file" > temp
mv temp file
精彩评论