web-dev-qa-db-fra.com

Insérer des lignes dans un fichier à partir d'une ligne spécifique

Je voudrais insérer des lignes dans un fichier en bash à partir d'une ligne spécifique.

Chaque ligne est une chaîne qui est un élément d'un tableau

line[0]="foo"
line[1]="bar"
...

et la ligne spécifique est "champs"

file="$(cat $myfile)"
for p in $file; do
    if [ "$p" = 'fields' ]
        then insertlines()     #<- here
    fi
done
35
Sadiel

Cela peut être fait avec 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

Utilisation -i pour enregistrer sur place au lieu d'imprimer sur stdout

sed -i 's/fields/fields\nNew Inserted Line/'

En tant que script bash:

#!/bin/bash

match='fields'
insert='New Inserted Line'
file='file.txt'

sed -i "s/$match/$match\n$insert/" $file
65
Chris Seymour

C'est certainement un cas où vous voulez utiliser quelque chose comme sed (ou awk ou Perl) plutôt que de lire une ligne à la fois dans une boucle Shell. Ce n'est pas le genre de chose que le Shell fait bien ou efficacement.

Vous pourriez trouver pratique d'écrire une fonction réutilisable. En voici une simple, bien qu'elle ne fonctionnera pas sur du texte totalement arbitraire (les barres obliques ou les métacaractères d'expression régulière vont confondre les choses):

function insertAfter # file line newText
{
   local file="$1" line="$2" newText="$3"
   sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file"
}

Exemple:

$ 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.
$ 
5
Mark Reed

sed est votre ami:

:~$ cat text.txt 
foo
bar
baz
~$ 

~$ sed '/^bar/\na this is the new line' text.txt > new_text.txt
~$ cat new_text.txt 
foo
bar
this is the new line
baz
~$ 
0
Oz123