一、sed命令簡介
sed是一種基於行的編輯器,專門用於從文件中選擇行文本,對其進行轉換或刪除。sed命令對於Unix和Linux用戶來說是必須掌握的技能之一。
二、sed命令參數解析
命令格式:sed [選項] 『command』 filename
選項:
- -n:禁止默認輸出,只能與p命令使用
- -e:命令選項後面可以接多個sed命令
- -f:指定從文件中讀取sed命令
command:是sed命令。例如:p、d、s/.old/.new/g等命令。
filename:文件名,在命令中可以使用多個文件名。
三、shell中常見的sed命令
1、shellsed命令詳解
shellsed是一個非互動式編輯器,它允許我們將sed命令與shell腳本結合起來對文件進行操作。下面是一個示例:
#!/bin/bash echo "The original file content is:" cat demo.txt echo "The edited file content is:" sed 's/is/are/g' demo.txt
以上腳本將文件demo.txt中的is替換為are,並輸出修改後的內容給我們查看。
2、shellsed刪除命令詳解
刪除文件指定字元串命令格式:sed 『/word/d『 filename,下面是一個示例:
#!/bin/bash echo "The original file content is:" cat demo.txt echo "The edited file content is:" sed '/apple/d' demo.txt
以上腳本將文件demo.txt中的所有含有apple的行都刪除並輸出修改後的內容給我們查看。
3、shellsed選取命令詳解
選取文件指定字元串命令格式:sed -n ‘/word/p’ filename,下面是一個示例:
#!/bin/bash echo "Only show lines containing apple:" sed -n '/apple/p' demo.txt
以上腳本將文件demo.txt中所有含apple字元串的行選取並輸出。
4、shellsed替換命令詳解
替換文件指定字元串命令格式:sed ‘s/old/new/g’ filename,下面是一個示例:
#!/bin/bash echo "The original file content is:" cat demo.txt echo "The edited file content is:" sed 's/George/Tom/g' demo.txt
以上腳本將demo.txt文件中所有的George替換為Tom,並輸出修改後的內容給我們查看。
5、shellsed追加命令詳解
在指定行後追加文字命令格式:sed ‘/word/a 新增文字’ filename,下面是一個示例:
#!/bin/bash echo "The original file content is:" cat demo.txt echo "The edited file content is:" sed '/apple/a Oranges' demo.txt
以上腳本將文件demo.txt中所有含apple的行後都追加Oranges,輸出修改後的內容給我們查看。
6、shellsed插入命令詳解
列出指定行並在該行前插入文字命令格式:sed -i ‘/apple/i 新增文字’ filename,下面是一個示例:
#!/bin/bash echo "The original file content is:" cat demo.txt echo "The edited file content is:" sed -i '/apple/i Oranges' demo.txt
以上腳本將文件demo.txt中所有含apple的行前都插入Oranges,輸出修改後的內容給我們查看。
總結
shellsed命令是Unix和Linux用戶必須掌握的技能之一,它具有非常豐富的用途和遠超我們上文所介紹的用法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/312986.html