从特定行开始在文件中插入行 [英] Insert lines in a file starting from a specific line
本文介绍了从特定行开始在文件中插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 bash 中从特定行开始将行插入到文件中.
I would like to insert lines into a file in bash starting from a specific line.
每一行都是一个字符串,它是数组的一个元素
Each line is a string which is an element of an array
line[0]="foo"
line[1]="bar"
...
具体的行是'fields'
and the specific line is 'fields'
file="$(cat $myfile)"
for p in $file; do
if [ "$p" = 'fields' ]
then insertlines() #<- here
fi
done
推荐答案
这可以用 sed 来完成: sed 's/fields/fields
New Inserted Line/'
This can be done with sed: sed 's/fields/fields
New Inserted Line/'
$ cat file.txt
line 1
line 2
fields
line 3
another line
fields
dkhs
$ sed 's/fields/fields
New Inserted Line/' file.txt
line 1
line 2
fields
New Inserted Line
line 3
another line
fields
New Inserted Line
dkhs
使用 -i
就地保存而不是打印到 stdout
Use -i
to save in-place instead of printing to stdout
sed -i 's/fields/fields
新插入的行/'
sed -i 's/fields/fields
New Inserted Line/'
作为 bash 脚本:
As a bash script:
#!/bin/bash
match='fields'
insert='New Inserted Line'
file='file.txt'
sed -i "s/$match/$match
$insert/" $file
这篇关于从特定行开始在文件中插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文