sed 應用筆記

sed 的筆記

1 sed 的指令

sed 的替換指令 有兩款。分別如下:

# 第一款
sed -i "s/${regexp_replaced}/${replacement}/g" ${file_path}

# 第二款,帶有 ${regexp_previous}
# ${regexp_previous} 可以出現 在 ${regexp_replaced} 的前面或者後面。
sed -i "/${regexp_previous}/s/${regexp_replaced}/${replacement}/g" ${file_path}

2 sed 的 例子

2.1 處理目標

假設 /etc/sysctl.conf 文件上,有如下的 指令。
都替換爲 net.ipv4.tcp_sack = 0

  • 替換前:
net.ipv4.tcp_sack=1
net.ipv4.tcp_sack = 1
net.ipv4.tcp_sack   =   1
net.ipv4.tcp_sack   =   xxxx
  • 替換後:
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0
net.ipv4.tcp_sack = 0

2.2 處理方法

可以使用以下兩款中的任意一款來進行替換。

# 第一款
sed -i "s/net.ipv4.tcp_sack\s*=\s*\S\+/net.ipv4.tcp_sack = 0/g" /etc/sysctl.conf

# 第二款,帶有 ${regexp_previous}
# 可以寫出更簡短的 指令。
sed -i "/net.ipv4.tcp_sack/s/=\s*\S\+/= 0/g" /etc/sysctl.conf

3 易用腳本

編寫了一個腳本。來方便以後使用:

function text_replace ()
{
	local ${file_path}=$1
	local ${regexp_replaced}=$2
	local ${replacement}=$3
	local ${regexp_previous}=$4
	
	if [ -z "${regexp_previous}" ]; then
		# without regexp_previous
		sed -i "s/${regexp_replaced}/${replacement}/g" ${file_path}
	else 
		# with regexp_previous
		sed -i "/${regexp_previous}/s/${regexp_replaced}/${replacement}/g" ${file_path}
	fi
}

4 notation of regexp in sed

regexp 中,一般知道以下的 notation 就夠用了。

notation description
. any char
\d digit. 1, 2, 3, …, etc.
\D not digit
\s white space, tab, space, …, etc.
\S not white space
\w alphabet or digit. 1, 2, 3, …, a, b, c, …, etc.
\W not (alphabet or digit). +, -, *, /, …, white space, etc.
+ repeat at least one
* repeat at least zero
^ begin of line
$ end of line
< begin of word
> end of word

TIPS:
使用 vim 來測試 regexp,是最直觀和快速的方法。

5 ref

Linux sed 命令

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章