2012-11-09 15 views
24

Ich möchte Zeilen in eine Datei in bash ausgehend von einer bestimmten Zeile einfügen.Einfügen von Zeilen in eine Datei ab einer bestimmten Zeile

Jede Zeile ist eine Zeichenkette, die

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

und der spezifischen Linie ein Element eines Arrays ist 'Felder'

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

Antwort

49

Dies kann mit sed durchgeführt werden: 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 

Verwendung -i an Ort und Stelle statt Druck zu stdout

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

Als Bash-Skript zu speichern:

#!/bin/bash 

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

sed -i "s/$match/$match\n$insert/" $file 
1

sed ist dein Freund:

:~$ 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 
~$ 
+2

, die nicht funktionieren; Sie benötigen einen Backslash und eine Newline in der sed-Befehlszeichenfolge nach dem 'a', nicht ein Leerzeichen. –

3

Dies ist definitiv ein Fall, in dem Sie etwas verwenden möchten wie sed (oder awk oder perl) anstatt in einer Shell-Schleife jeweils eine Zeile zu lesen. Dies ist nicht das, was die Shell gut oder effizient macht.

Sie könnten es nützlich finden, eine wiederverwendbare Funktion zu schreiben. Hier ist ein einfaches, aber es ist nicht auf funktionieren voll beliebigen Text (Schrägstriche oder einen regulären Ausdruck Metazeichen werden die Dinge verwirren):

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

Beispiel:

$ 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. 
$ 
Verwandte Themen