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

Bash 在文件中从特定行开始插入行,bash,sed,Bash,Sed,我想在bash的文件中插入从特定行开始的行 每行是一个字符串,它是数组的一个元素 line[0]="foo" line[1]="bar" ... 具体行是“字段” file="$(cat $myfile)" for p in $file; do if [ "$p" = 'fields' ] then insertlines() #<- here fi done file=“$(cat$myfile)” 对于$file中的p;做 如果[“$p”=“

我想在bash的文件中插入从特定行开始的行

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

line[0]="foo"
line[1]="bar"
...
具体行是“字段”

file="$(cat $myfile)"
for p in $file; do
    if [ "$p" = 'fields' ]
        then insertlines()     #<- here
    fi
done
file=“$(cat$myfile)”
对于$file中的p;做
如果[“$p”=“字段”]
然后insertlines()35;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
~$ 

这可以通过sed完成:
sed的/fields/fields\n新插入的行/'

$ 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的/fields/fields\n新插入的行/'

$ 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
作为bash脚本:

#!/bin/bash

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

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

在这种情况下,您肯定希望使用类似于
sed
(或
awk
perl
)的东西,而不是在shell循环中一次读取一行。这不是shell能够很好或有效地完成的事情

您可能会发现编写一个可重用函数很方便。下面是一个简单的例子,尽管它不能处理完全任意的文本(斜杠或正则表达式元字符会混淆问题):

例如:

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

或另一个带有
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

那是行不通的;在sed命令字符串中,在
a
之后需要一个反斜杠和换行符,而不是空格。使用
sed-i
时,这会重写整个文件,但会使用
sed
的替换,还是类似于在文本编辑器中打开文件并手动插入字符串?我问这个问题是因为我需要对一个大文件执行此操作,而一遍又一遍地写这么多内容将花费很长时间,并且会更快地耗尽我的SSD和HDD。如果打开一个文件,手动插入字符串并保存它,您希望文本编辑器实际执行什么操作?sed-我不再工作了。在Solaris11.4上,它抛出“非法选项-i”