![](/img/trans.png)
[英]sed -i is not working on solaris system while removing 1st line from file
[英]How do I insert text to the 1st line of a file using sed?
嗨,到目前為止,我正在嘗試使用 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
時,我會看到第一行文本,但是只要我輸入sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
我在第 2 行看不到我應該做的信息,這是 ssl_certificate_key /etc/example/live/example.com/privkey.pem;
所以我要總結的問題
假設你有一個這樣的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
請注意那些sed
表達式中的數字1
- 這在sed
術語中稱為地址。 它告訴您后面的命令要在哪一行進行操作。
如果您的文件不包含您要尋址的行,則不會執行sed
命令。 這就是為什么你不能在第 1 行插入/追加的原因,如果你的文件是空的。
而不是使用流編輯器,追加(到空文件),只需使用外殼重定向>>
:
echo "content" >> file
如果您確保輸入文件至少有一行,您的命令將起作用:
[ "$(wc -l < test)" -gt 0 ] || printf '\n' >> test
sed -i -e '1 i/etc/example/live/example.com/fullchain.pem;\' test
您的問題源於sed
無法找到您告訴它寫入的行,例如:
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
嘗試在test
的第 1 行寫入插入,但此時該行不存在。 如果您已將文件創建為:
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;"
您告訴sed
在第 2 行插入以下數據,該數據當時不存在,因此sed
無法編輯文件。
因此,對於文件中的首行或最后一行,您不應該使用sed
因為簡單的>
和>>
流重定向已經綽綽有余。
我假設任何搜索如何在文件的開頭/結尾插入/附加文本的人可能也需要知道如何做另一個。
cal | \
gsed -E \
-e '1i\{' \
-e '1i\ "lines": [' \
-e 's/(.*)/ "\1",/' \
-e '$s/,$//' \
-e '$a\ ]' \
-e '$a\}'
這是cal
輸出管道輸送到gnu- sed
(稱為gsed
上經由安裝MACOS brew.sh )與正則表達式擴展( -E
)和6“腳本”應用於( -e
)和換行與轉義\\
以提高可讀性。 腳本 1 和 2 使用1i\\
來“在第 1 行,插入”。 腳本 5 和 6 使用$a\\
來“在 <last> 行,追加”。 我垂直對齊文本輸出以使代碼代表結果中的預期內容。 腳本 3 和 4 進行替換(后者僅適用於“行 <last>”)。 結果是將命令輸出轉換為有效的 JSON。
{
"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 ",
" "
]
}
如需幫助使其與 sed 的 macos/BSD 版本一起使用,請在此處查看我的回答。
在 macOS 上使用 sed 將文本插入第一行並將其余部分放在新行上,這對我有用
sed -i '' '1 i \
Insert
' ~/Downloads/File-path.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.