插入线在一个文件从特定行开始 [英] Insert lines in a file starting from a specific line

查看:126
本文介绍了插入线在一个文件从特定行开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个特定的行插入行到在bash启动文件。

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

 行[0] =富
行[1] =栏
...

和特定行是字段

 文件=$(猫$ MYFILE)
在$文件p;做
    如果[$ P='域']
        然后insertlines()#< - 在这里
    科幻
DONE


解决方案

这可以用做sed的: SED的/场/场\\ n新插入的行/

  $ file.txt的猫
1号线
2号线
领域
3号线
另一条线
领域
dkhs$ sed的'S /场/场\\ n新插入的行/'file.txt的
1号线
2号线
领域
新插入的行
3号线
另一条线
领域
新插入的行
dkhs

使用 -i 保存就地而不是打印到标准输出

SED -i'S /场/场\\ n新插入的行/

作为一个bash脚本:

 #!/斌/庆典比赛='场'
插入='新插入线
文件='file.txt的SED -iS / $匹配/ $匹配\\ n $的插入/$文件

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

and the specific line is 'fields'

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

解决方案

This can be done with 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

Use -i to save in-place instead of printing to stdout

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

As a bash script:

#!/bin/bash

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

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

这篇关于插入线在一个文件从特定行开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆