Я хочу добавить кое-что в конец определенной строки (иметь определенный символ). 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!
Я бы, наверное, выбрал решение sed
Джона, но, поскольку вы также спрашивали о awk
:
$ 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}'
Это выводит:
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.
Объяснение того, как это работает, может быть полезным. Подумайте о сценарии awk
следующим образом с условиями слева и командами справа:
/^Line2:/ {$0=$0" Please help me"}
{print}
Эти два предложения awk
выполняются для каждой отдельной обрабатываемой строки.
Если строка соответствует регулярному выражению ^Строка2:
(что означает «Строка2:» в начале строки), вы изменяете $0
, добавляя нужную строку ($0
— это вся строка, прочитанная в awk
).
Если строка соответствует пустому условию (этому будут соответствовать все строки), выполняется print
. Это выводит текущую строку $0
.
Итак, вы можете видеть, что это простая программа, которая изменяет строку там, где это необходимо, и выводит строку, измененную или нет.
Кроме того, вы можете использовать /^Line2:/
в качестве ключа даже для решения sed
, чтобы не выбирать Line2
. в середине текста или от Строка20
до Строка29
, Строка200
по Строка299
и так далее:
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