2012-11-09 9 views
24

特定の行から始まるファイルに行を挿入したいとします。特定の行から始まるファイルに行を挿入します。

各行は、アレイ

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

の要素である文字列であり、特定の行には、sedの 'フィールド'

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

答えて

49

これは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はbashスクリプトとしてインプレースの代わりに印刷のstdout

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

に保存するには:

#!/bin/bash 

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

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

であるあなたの友達です:

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

。スペースではなく 'a'の後にsedコマンド文字列にバックスラッシュと改行が必要です。 –

3

これは間違いなくあなたのようなものを使用したい場合です(またはawkまたは)を使用してください。これは、シェルがうまくやりとりするようなものではありません。

再利用可能な関数を書くと便利でしょう。それは完全に任意のテキストを上に動作しないでしょうが、ここで簡単なものは、(スラッシュや正規表現のメタ文字は物事を混同します)、です:

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. 
$ 
関連する問題