簡體   English   中英

sed用包含嵌套引號的字符串替換行號處的整行

[英]sed replace entire line at line number with a string that contains nested quotes

我想用sed用我自己的字符串替換某些行,該字符串必須包含一些嵌套的引號,因為它將被另一個程序及其本身執行的命令讀取。

sed -i '63s/^.*$/mystring/' file.txt

其中63是行號, ^.*$選擇要替換的整行, mystring是替換字符串, file.txt是要處理的文件。

比如說我想讓mystring exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"' mystring exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'我應該怎么做呢?我已經嘗試了轉義引號。

例如,您可以執行以下操作:

sed -i.bak "63s|^.*$|$string|" file.txt

一種方法是從文件中獲取它。 另外,請注意,必須使用sed中的雙引號來擴展變量。 最后,對sed使用另一個定界符,並將$string存儲在變量中。 例如, | 這是因為您的$string包含斜杠,並使sed看到諸如sed "s/^.*$/something/blabla/"類的命令,它是如此之多。

同樣, -i.bak創建file.txt > file.txt.bak的備份。

測試

$ cat a
hel
lo
ooo
bye
$ cat b
exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'
$ string=$(cat b)

$ sed "3s|^.*$|$string|" a
hel
lo
exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'
bye

如果您不想進行變量分配,則只需在替換字符串中轉義有問題的字符即可。 在這種情況下,只需在雙引號"

sed -i.bak "63s|^.*$|exec: echo 'echo \"127.0.0.1 localhost\" >> /etc/hosts\"'|" file.txt
                                      ^                    ^               ^

測試

$ sed "3s|^.*$|exec: echo 'echo \"127.0.0.1 localhost\" >> /etc/hosts\"'|" a
hel
lo
exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'
bye

這可能適合您(GNU sed和Bash):

cat <<\! >quoted-text.txt
exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'
!

sed $'63{r quoted-text.txt\nd}' file

將困難的文本行放入文件中,並通過讀取該文件並刪除原始行來替換所需的行。

您也可以嘗試

sed -i "63s~.*~exec: echo \'echo \"127.0.0.1 localhost\" >> /etc/hosts\"\'~g" file

它只需要轉義引號和不同的sed分隔符。

*例:

$ sed "2s~.*~exec: echo \'echo \"127.0.0.1 localhost\" >> /etc/hosts\"\'~g" file
abc, xym krg plf, 763, bla
exec: echo 'echo "127.0.0.1 localhost" >> /etc/hosts"'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM