我在這裏找到了有趣的讨論,並尝試了
sed
提供的解決方案
How to insert a text at the beginning of a file?
它適用於普通文字,但不適用於將文字儲存在變數中的情况。
[email protected]:~$ cat file.txt
1
2
3
[email protected]:~$
添加文字(
<added text>
)到檔案的開頭
[email protected]:~$ sed -i '1s/^/<added text>\n/' file.txt
[email protected]:~$
有效!
[email protected]:~$ cat file.txt
<added text>
1
2
3
[email protected]:~$
但是,当我尝試使用變數時,它不再起作用了。
[email protected]:~$ var='Text 1'
[email protected]:~$ echo $var
Text 1
[email protected]:~$
[email protected]:~$ cat file.txt
1
2
3
[email protected]:~$ sed -i '1s/^/"$var"\n/' file.txt
[email protected]:~$ cat file.txt
"$var"
1
2
3
[email protected]:~$
代替
"$var"
,我怎麼稱呼
$var
的實際value
在
sed
命令?
最新回復
- 5月前1 #
相似問題
- bash:使用sed批量重命名檔案bashshellsedfilerename2021-01-09 17:28
- regex:仅使用sed或awk从html頁面提取URL的最簡單方法htmlregexbashsedawk2021-01-09 16:56
- bash:查詢唯一名稱的频率bashshellscripttextprocessingawksed2021-01-06 13:54
- bash:了解sed正則表達式模式bashsed2021-01-05 17:27
- bash:使用sed將所有反斜杠替換為正斜杠bashshellsed2021-01-03 05:23
問题是您有-按照建議-封闭了
sed
單引號說明' ... '
.但是,在單引號內包含變數擴充套件,例如$var
被禁用,该表達式保持逐字記錄。作為解決方案,您可以將說明用双引號引起来:
但是請註意,我建議為此目的使用"插入"命令:
將插入
$var
的內容 在第1行之前。