我有一个脚本文件,我需要用另一个脚本修改,在第8行插入一个文本。
要插入的字符串:Project_Name=sowstest,到一个名为start的文件中。
我尝试使用awk和sed,但我的命令变得混乱。
我有一个脚本文件,我需要用另一个脚本修改,在第8行插入一个文本。
要插入的字符串:Project_Name=sowstest,到一个名为start的文件中。
我尝试使用awk和sed,但我的命令变得混乱。
当前回答
一个成功的答案
ed file << END
8i
Project_Name=sowstest
.
w
q
END
. 在它自己的行结束输入模式;w写道;q退出。GNU ed有一个wq命令来保存和退出,但旧ed没有。
进一步阅读:https://gnu.org/software/ed/manual/ed_manual.html
其他回答
对于那些使用非gnu的SunOS的人来说,下面的代码将会有所帮助:
sed '1i\^J
line to add' test.dat > tmp.dat
^J用^V+^J插入 在'1i之后添加换行符。 \必须是该行的最后一个字符。 命令的第二部分必须在第二行中。
OS X / macOS / FreeBSD sed
-i标志在macOS sed和GNU sed上的工作方式不同。
下面是在macOS / OS X上使用它的方法:
sed -i '' '8i\
8 This is Line 8' FILE
更多信息见男子1 sed。
sed -e '8iProject_Name=sowstest' -我开始使用GNU sed
示例运行:
[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file
[root@node23 ~]# cat -An a_file
1 Line #1$
2 Line #2$
3 xxx inserted line xxx$
4 Line #3$
5 Line #4$
6 Line #5$
7 Line #6$
8 Line #7$
9 Line #8$
10 Line #9$
11 Line #10$
[root@node23 ~]#
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file
1 Line #1
2 Line #2
3 xxx inserted line xxx
4 Line #3
5 xxx (inserted) "line" xxx
6 Line #4
7 Line #5
8 Line #6
9 Line #7
10 Line #8
11 Line #9
12 Line #10
[root@node23 ~]#
谢谢umläute
sed -i "" -e $'4 a\\\n''Project_Name=sowstest' filename
下面的代码在macOS上很有用,可以在4之后添加新行
为了循环我创建了一个文件夹数组,在mac zsh中迭代它们
for foldercc in $foldernames;
sed -i "" -e $'4 a\\\n''Project_Name=sowstest' $foldercc/filenames;
sed -i "" -e $'4 a\\\n''Project_Name=sowstest' start
这一行在macOS中工作正常