您好我正在尝试使用sed将文本添加到文件的第一行 到目前为止,我试过了
#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
这不起作用 也尝试了
#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test
这似乎也不起作用 奇怪的是,当我尝试
时#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test
我使用cat test
时会显示第1行文字
但只要我输入sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
我无法看到我在第2行可以做的信息,这是ssl_certificate_key /etc/example/live/example.com/privkey.pem;
所以我的问题是夏天
答案 0 :(得分:4)
假设你有file
这样:
one
two
然后追加到第一行:
$ sed '1 s_$_/etc/example/live/example.com/fullchain.pem;_' file
one/etc/example/live/example.com/fullchain.pem;
two
要在第一行之前插入:
$ sed '1 i /etc/example/live/example.com/fullchain.pem;' file
/etc/example/live/example.com/fullchain.pem;
one
two
或者,在第一行之后追加:
$ sed '1 a /etc/example/live/example.com/fullchain.pem;' file
one
/etc/example/live/example.com/fullchain.pem;
two
请注意这些1
表达式中的sed
个数字 - 在sed
术语中称为the address。它告诉您后面的行 the command是否可以运行。
如果您的文件不包含您正在寻址的行,则不会执行sed
命令。这就是为什么如果您的文件为空,则无法在第1行插入/附加。
不使用流编辑器,而是附加(到空文件),只需使用shell重定向>>
:
echo "content" >> file
答案 1 :(得分:1)
如果您确保输入文件至少包含一行,那么您的命令将起作用:
[ "$(wc -l < test)" -gt 0 ] || printf '\n' >> test
sed -i -e '1 i/etc/example/live/example.com/fullchain.pem;\' test
答案 2 :(得分:1)
您的问题源于CREATE TABLE `calendar_events` (
`ID` int(11) NOT NULL,
`title` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
`description` varchar(1000) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
无法找到您要写入的行,例如:
sed
尝试写入touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
的第1行插入,但此时此行不存在。如果您已将文件创建为:
test
它不会抱怨,但你会有一个额外的线。同样,当你打电话:
echo -en "\n" > test
sed -i '1i/etc/example/live/example.com/fullchain.pem;\' test
您告诉sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
在第2行插入以下数据,但此时sed
无法编辑该文件。
因此,对于文件中的初始行或最后一行,您不应使用sed
,因为简单的sed
和>
流重定向已足够。
答案 3 :(得分:0)
我认为,任何搜索如何将文本插入/添加到文件开头/结尾的人可能也需要知道如何做另一个。
cal | \
gsed -E \
-e '1i\{' \
-e '1i\ "lines": [' \
-e 's/(.*)/ "\1",/' \
-e '$s/,$//' \
-e '$a\ ]' \
-e '$a\}'
这是cal
输出,通过扩展RegEx(sed
)和6“通过管道传输到gnu-gsed
(在通过brew.sh安装的macOS上称为-E
)上脚本”({-e
)和换行符\
来换行,以提高可读性。脚本1和2使用1i\
来“在第1行插入”。脚本5和6使用$a\
来“在
{
"lines": [
" October 2019 ",
"Su Mo Tu We Th Fr Sa ",
" 1 2 3 4 5 ",
" 6 7 8 9 10 11 12 ",
"13 14 15 16 17 18 19 ",
"20 21 22 23 24 25 26 ",
"27 28 29 30 31 ",
" "
]
}