到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:
文件内容
some text at the beginning
结果
<added text> some text at the beginning
它很相似,但是我不想用它创建任何新的行…
如果可能的话,我希望用sed来做这件事。
到目前为止,我已经能够找出如何在文件的开头添加一行,但这并不完全是我想要的。我将用一个例子来说明:
文件内容
some text at the beginning
结果
<added text> some text at the beginning
它很相似,但是我不想用它创建任何新的行…
如果可能的话,我希望用sed来做这件事。
当前回答
插入换行符:
sed '1i\\'
其他回答
如果文件只有一行,你可以使用:
sed 's/^/insert this /' oldfile > newfile
如果它不止一行。之一:
sed '1s/^/insert this /' oldfile > newfile
sed '1,1s/^/insert this /' oldfile > newfile
我已经包括了后者,以便您知道如何进行行范围。这两种方法都用要插入的文本“替换”受影响行的开始行标记。您还可以(假设您的sed足够现代)使用:
sed -i 'whatever command you choose' filename
进行就地编辑。
注意,在OS X上,sed -i <pattern>文件失败。但是,如果您提供了一个备份扩展名sed -i old <pattern> file,那么file将在file的位置被修改。旧的是创造出来的。然后您可以删除文件。老在你的剧本里。
我找到的最简单的解决方法是:
echo -n "<text to add>" | cat - myFile.txt | tee myFile.txt
注:
Remove | tee myFile.txt if you don't want to change the file contents. Remove the -n parameter if you want to append a full line. Add &> /dev/null to the end if you don't want to see the output (the generated file). This can be used to append a shebang to the file. Example: # make it executable (use u+x to allow only current user) chmod +x cropImage.ts # append the shebang echo '#''!'/usr/bin/env ts-node | cat - cropImage.ts | tee cropImage.ts &> /dev/null # execute it ./cropImage.ts myImage.png
插入换行符:
sed '1i\\'
博士 -
考虑使用ex。由于您想要给定行的前面,那么语法基本上与sed相同,但“就地编辑”选项是内置的。
我无法想象一个你有sed但没有ex/vi的环境,除非它是一个MS Windows盒子,有一些特殊的“sed.exe”,也许。
Sed和grep从ex / vi演变而来,所以说Sed语法与ex语法相同可能更好。
您可以将行号更改为#1以外的内容,或者搜索一行并更改该行。
source=myFile.txt
Front="This goes IN FRONT "
man true > $source
ex -s ${source} <<EOF
1s/^/$Front/
wq
EOF
$ head -n 3 $source
This goes IN FRONT TRUE(1) User Commands TRUE(1)
NAME
长的版本,我推荐ex(或者ed,如果你是一个很酷的孩子)。
我喜欢ex,因为它是可移植的,非常强大,允许我在不需要GNU(甚至BSD)扩展的情况下进行就地编写和/或备份。
此外,如果你知道ex的方法,那么你就知道如何在vi和vim中做它,如果那是你的专长的话。 注意,当我们使用"i"nsert和使用echo时,EOF没有被引用:
str="+++ TOP +++" && ex -s <<EOF
r!man true
1i
`echo "$str"`
.
"0r!echo "${str}"
wq! true.txt
EOF
0 r !Echo "${str}"也可以用作:0read!或:0 r !你可能在vi模式中使用过(实际上是一样的),但是:在这里是可选的,一些实现不支持“r”ead地址为零。 “r”直接读取到特殊的行#0(或从行1)会自动将所有内容“下”,然后只需:wq保存更改。
$ head -n 3 true.txt | nl -ba
1 +++ TOP +++
2 TRUE(1) User Commands TRUE(1)
3
而且,大多数经典的sed实现都没有ex默认应该有的扩展(如\U&)。