2012-11-09 31 views
24

Tôi muốn chèn các dòng vào một tệp trong bash bắt đầu từ một dòng cụ thể.Chèn các dòng vào một tệp bắt đầu từ một dòng cụ thể

Mỗi dòng là một chuỗi đó là một phần tử của một mảng

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

và dòng cụ thể là 'lĩnh vực'

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

Trả lời

49

Điều này có thể được thực hiện với 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 

Sử dụng -i để lưu tại chỗ thay vì in ấn để stdout

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

Như một kịch bản bash:

#!/bin/bash 

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

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

sed là bạn của bạn:

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

rằng sẽ không làm việc; bạn cần một dấu gạch chéo ngược và một dòng mới trong chuỗi lệnh sed sau 'a', không phải là dấu cách. –

3

Đây chắc chắn là một trường hợp bạn muốn sử dụng cái gì đó như sed (hoặc awk hoặc perl) thay vì đọc một dòng tại một thời điểm trong vòng kết nối. Đây không phải là loại vỏ mà hoạt động tốt hay hiệu quả.

Bạn có thể thấy tiện dụng khi viết chức năng có thể tái sử dụng. Dưới đây là một đơn giản, mặc dù nó sẽ không làm việc trên văn bản đầy đủ tùy ý (dấu gạch chéo hoặc metacharacters biểu thức chính quy sẽ nhầm lẫn giữa việc):

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

Ví dụ:

$ 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. 
$ 
Các vấn đề liên quan