从特定行开始插入文件中

  • 本文关键字:插入 文件 开始 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

这可以用sed: sed 's/fields/fieldsnNew Inserted Line/'

来完成
$ cat file.txt 
line 1
line 2 
fields
line 3
another line 
fields
dkhs
$ sed 's/fields/fieldsnNew 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/fieldsnNew Inserted Line/'

作为bash脚本:

#!/bin/bash
match='fields'
insert='New Inserted Line'
file='file.txt'
sed -i "s/$match/$matchn$insert/" $file

或用 sed

的一个示例

准备test.txt文件:

echo -e "line 1nline 2nline 3nline 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

这绝对是您要使用诸如sed(或awkperl)之类的东西,而不是一次在Shell循环中一次读取一行。这不是外壳做得很好或有效的事情。

您可能会觉得编写可重复使用的功能很方便。这是一个简单的文字,尽管它无法在全保余文本上使用(Slashes或正则表达式Metacharacters会混淆事物):

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

是您的朋友:

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

相关内容

  • 没有找到相关文章

最新更新