2012-11-09 8 views
24

Chciałbym wstawić linie do pliku w bashu począwszy od określonego wiersza.Wstawianie wierszy do pliku rozpoczynając od określonej linii.

Każda linia jest ciągiem znaków, który jest elementem tablicy

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

i konkretnej linii jest 'Pola'

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

Odpowiedz

49

Można to zrobić za pomocą 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 

Zastosowanie -i zapisać w miejscu, zamiast drukowania do stdout

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

jako skrypt bash:

#!/bin/bash 

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

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

sed jest twoim przyjacielem:

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

że nie będzie działać; potrzebujesz "backslash" i "newline" w ciągu polecenia sed po "a", a nie spacji. –

3

Jest to z pewnością przypadek, w którym chcesz używać coś takiego sed (lub awk lub perl) zamiast odczytywać po jednej linii w pętli powłoki. To nie jest rzecz, którą powłoka wykonuje dobrze lub sprawnie.

Przydaje się możliwość pisania funkcji wielokrotnego użytku. Oto prosta, choć nie będzie działać na całkowicie dowolny tekst (ukośniki lub foremnych metaznakami ekspresyjne będą mylić rzeczy):

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

Przykład:

$ 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. 
$ 
Powiązane problemy