在Linux中,sed
(stream editor)是一個用于對文本文件進行處理的命令行工具
sed 's/pattern/replacement/g' input_file > output_file
要在輸入文件中插入內容,可以使用以下方法:
sed 's/^/insert_content/' input_file > output_file
這將在每一行的開頭插入insert_content
。
sed 's/$/insert_content/' input_file > output_file
這將在每一行的末尾插入insert_content
。
sed 's/\(pattern\)/\1\
insert_content/' input_file > output_file
這將在匹配到pattern
的位置插入insert_content
。\1
表示第一個捕獲組的內容,即匹配到的內容。\n
表示換行符。
例如,假設我們有一個名為example.txt
的文件,內容如下:
apple
banana
orange
我們想要在banana
行前插入一行fruit1
,可以使用以下命令:
sed '/banana/a\
fruit1' example.txt > example_modified.txt
這將生成一個名為example_modified.txt
的文件,內容如下:
apple
fruit1
banana
orange
請注意,這些示例僅適用于單個插入。如果您需要在多行上插入內容,可以使用更復雜的sed
腳本。