使用 sed 为每行输出添加前缀
Add prefix to each line of output with sed
好的,谷歌搜索几分钟后,这似乎是在每行输出前加上 sed
前缀的常规方法
但是我得到一个我不明白的错误。
这是什么意思,我该如何解决?
$ sed 's/^/#/' test.txt
sed: -e expression #1, char 0: no previous regular expression
我的 test.txt 长什么样 - 这真的只是一个测试
### test.txt
a
b
c
d
e
f
g
h
哦是的..版本
$ sed --version
GNU sed version 4.2.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.
下面的代码将使用捕获组执行相同的操作,但不会触及空行。
sed 's/^\(.\)/#/' test.txt
如果您还想在空白行的开头添加 #
,请试试这个。
sed 's/^\(.\|\)/#/' file
示例:
$ cat f
a
b
$ sed 's/^\(.\)/#/' f
#a
#b
$ sed 's/^\(.\|\)/#/' f
#a
#
#b
你也可以使用awk
来解决这个问题:
cat file
a
b
将#
添加到所有行:
awk '{[=11=]="#"[=11=]}1' file
#a
#
#b
将#
添加到所有非空行
awk 'NF{[=12=]="#"[=12=]}1' file
#a
#b
好的,谷歌搜索几分钟后,这似乎是在每行输出前加上 sed
但是我得到一个我不明白的错误。
这是什么意思,我该如何解决?
$ sed 's/^/#/' test.txt
sed: -e expression #1, char 0: no previous regular expression
我的 test.txt 长什么样 - 这真的只是一个测试
### test.txt
a
b
c
d
e
f
g
h
哦是的..版本
$ sed --version
GNU sed version 4.2.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.
下面的代码将使用捕获组执行相同的操作,但不会触及空行。
sed 's/^\(.\)/#/' test.txt
如果您还想在空白行的开头添加 #
,请试试这个。
sed 's/^\(.\|\)/#/' file
示例:
$ cat f
a
b
$ sed 's/^\(.\)/#/' f
#a
#b
$ sed 's/^\(.\|\)/#/' f
#a
#
#b
你也可以使用awk
来解决这个问题:
cat file
a
b
将#
添加到所有行:
awk '{[=11=]="#"[=11=]}1' file
#a
#
#b
将#
添加到所有非空行
awk 'NF{[=12=]="#"[=12=]}1' file
#a
#b