Вставить строки в файл, начинающийся с определенной строки
Я хотел бы вставить строки в файл в bash, начиная с определенной строки.
Каждая строка представляет собой строку, которая является элементом массива
line[0]="foo"
line[1]="bar"
...
а конкретная строка - "поля"
file="$(cat $myfile)"
for p in $file; do
if [ "$p" = 'fields' ]
then insertlines() #<- here
fi
done
Ответы
Ответ 1
Это можно сделать с помощью sed: sed 's/fields/fields\nNew Inserted Line/'
$ cat file.txt
line 1
line 2
fields
line 3
another line
fields
dkhs
$ sed 's/fields/fields\nNew Inserted Line/' file.txt
line 1
line 2
fields
New Inserted Line
line 3
another line
fields
New Inserted Line
dkhs
Используйте -i
для сохранения на месте вместо печати на stdout
sed -i 's/fields/fields\nNew Inserted Line/'
Как bash script:
#!/bin/bash
match='fields'
insert='New Inserted Line'
file='file.txt'
sed -i "s/$match/$match\n$insert/" $file
Ответ 2
Это определенно случай, когда вы хотите использовать что-то вроде sed
(или awk
или perl
) вместо того, чтобы читать одну строку за раз в цикле оболочки. Это не то, что оболочка делает хорошо или эффективно.
Вам может показаться удобным написать функцию многократного использования. Здесь простой, хотя он не будет работать на полностью произвольном тексте (слэши или метасимволы регулярного выражения будут путать вещи):
function insertAfter # file line newText
{
local file="$1" line="$2" newText="$3"
sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file"
}
Пример:
$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The quick brown fox jumps over a lazy dog.
$ insertAfter foo.txt \
"Now is the time for all good men to come to the aid of their party." \
"The previous line is missing 'bjkquvxz.'"
$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The previous line is missing 'bjkquvxz.'
The quick brown fox jumps over a lazy dog.
$
Ответ 3
sed - ваш друг:
:~$ cat text.txt
foo
bar
baz
~$
~$ sed '/^bar/a this is the new line' text.txt > new_text.txt
~$ cat new_text.txt
foo
bar
this is the new line
baz
~$