54

我想从特定行开始在 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

4 回答 4

98

这可以通过 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
于 2012-11-09T21:51:17.767 回答
11

或者另一个例子sed

准备一个test.txt文件:

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

cat /tmp/test.txt
line 1
line 2
line 3
line 4

在文件中添加新行test.txt

sed -i '2 a line 2.5' /tmp/test.txt
# sed for in-place editing (-i) of the file: 'LINE_NUMBER a-ppend TEXT_TO_ADD'

cat /tmp/test.txt
line 1
line 2
line 2.5
line 3
line 4
于 2019-11-18T01:38:35.040 回答
7

这绝对是您想要使用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.
$ 
于 2012-11-09T22:11:16.267 回答
-1

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
~$ 
于 2012-11-09T21:51:12.757 回答