从特定行开始在文件中插入行

时间:2012-11-09 21:42:58

标签: bash sed

我想从特定行开始在bash中插入行。

每一行都是一个字符串,它是数组的元素

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

,具体行是'fields'

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

4 个答案:

答案 0 :(得分:62)

这可以使用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保存到位,而不是打印到stdout

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

作为bash脚本:

#!/bin/bash

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

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

答案 1 :(得分:5)

这绝对是您希望使用sed(或awkperl)之类的内容而不是在shell循环中一次读取一行的情况。这不是shell做得好或有效的事情。

您可能会发现编写可重用函数很方便。这是一个简单的,虽然它不适用于完全任意的文本(斜杠或正则表达式元字符会混淆事物):

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

答案 2 :(得分:0)

sed是你的朋友:

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

答案 3 :(得分:0)

或者用sed注释一个例子:

echo -e "line 1\nline 2\nline 3\nline 4" > /tmp/test.py
cat /tmp/test.py
line 1
line 2
line 3
line 4

sed -i '2 a line 2.5' /tmp/test.py    # sed for inside of the file 'LINE_NUMBER append TEXT'
cat /tmp/test.py
line 1
line 2
line 2.5
line 3
line 4