我正在嘗試在一個檔案中插入一行,該檔案將有一個 sed 命令在另一個檔案中插入一行,如下所示:想要將此行添加sed -i '1s/^/insideFile\n/' secondFile.sh到第65行firstfile.txt
我試過了:
sed -i '65s/^/\'sed -i \'1s/^/insideFile\n/\' secondFile.sh\'\n/' firstfile.sh
但無法逃脫'
也試過
sed -i "65s/^/'sed -i "1s/^/topLine\n/" $FILE_HOME_LOCAL_FILE'\n/" secondFile.sh
但得到了 sed: -e 運算式 #1, char 18: `s 的未知選項
uj5u.com熱心網友回復:
你可以使用這個sed:
sed -i.bak "65s~^~sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\n~" firstfile.sh
筆記:
- 使用備用分隔符
~來避免轉義/ - 為您的命令使用雙引號
sed以避免轉義單引號 - 用于
\\\\插入單個\ - 使用
\\n內部雙引號插入換行符
或者使用i(insert) 而不是s(substitute):
sed -i.bak "65i\\
sed -i '1s/^/insideFile\\\\n/' secondFile.sh\\
" firstfile.sh
最干凈的解決方案是創建一個像這樣的 sed 腳本,從而避免所有參考和額外的轉義:
cat ins.sed
65i\
sed -i '1s/^/insideFile\\n/' secondFile.sh
然后將其用作:
sed -i.bak -f ins.sed firstfile.sh
uj5u.com熱心網友回復:
雖然sed允許您做這些事情,但當涉及斜杠和其他控制字符時,它變得有點麻煩。因此,awk改用這個可能是有益的:
$ awk '(FNR==65){print "sed -i \0421s/^/insideFile\\n/\042 secondFile.sh"}1' firstfile.txt > firstfile.new
$ mv firstfile.new > firstfile.txt
有就地的可能性,但如果你想到它。Inplace 只不過是在之后進行重命名。這正是sed正在做的事情。
uj5u.com熱心網友回復:
我想將此行添加
sed -i '1s/^/insideFile\n/' secondFile.sh到第 65 行firstfile.txt
腳本解決方案:
#!/bin/bash
## uncomment to make sure firstfile.txt has at least 65 (e.g. 66) lines
# for index in {1..66}; do
# echo -e "$index" >> firstfile.txt
# done
# prepare the insert text, escaping the newline character twice
text="sed -i '1s/^/insideFile\\\\n/'"
# append to 65th line
sed -i '' "65i\\
$text
" firstfile.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/518151.html
標籤:linuxsed
上一篇:將特定列轉換為行
