我想从特定行开始在bash中插入行.
每一行都是一个字符串,它是一个数组的元素
line[0]="foo"
line[1]="bar"
...
Run Code Online (Sandbox Code Playgroud)
而具体的行是'字段'
file="$(cat $myfile)"
for p in $file; do
if [ "$p" = 'fields' ]
then insertlines() #<- here
fi
done
Run Code Online (Sandbox Code Playgroud)
Chr*_*our 66
这可以用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
Run Code Online (Sandbox Code Playgroud)
使用-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
Run Code Online (Sandbox Code Playgroud)
或者另一个例子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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
绝对是在这种情况下,您想使用类似sed(或awk或perl)的东西,而不是一次在Shell循环中读取一行。这不是外壳能很好或有效地完成的事情。
您可能会发现编写可重用的函数很方便。这是一个简单的示例,尽管它不适用于完全任意的文本(斜杠或正则表达式元字符会混淆事物):
function insertAfter # file line newText
{
local file="$1" line="$2" newText="$3"
sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file"
}
Run Code Online (Sandbox Code Playgroud)
例:
$ 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.
$
Run Code Online (Sandbox Code Playgroud)