歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> AIX下系統sed使用詳解

AIX下系統sed使用詳解

日期:2017/2/28 14:55:26   编辑:Linux教程
使用sed去修改或者刪除文本中的字符或者字符串。
pg func.txt
0at$the@begining^M
The#file#name#is#func,^M
9and%it's%suffix%is .txt

1.查找包含"#"的行:
awk '$0 ~ /#/' func.txt
The#file#name#is#func,^M

2.將包含"#"的行中第一個"#"替換為空格:
sed -n 's/#/ /p' func.txt
The file#name#is#func,^M

3.替換行中所有的"#":
sed 's/#/ /g' func.txt
0at$the@begining^M
The file name is func,^M
9and%it's%suffix%is .txt

4.替換行開頭的數字:
sed 's/^[0-9]*//g' func.txt
at$the@begining^M
The#file#name#is#func,^M
and%it's%suffix%is .txt

5.將結尾的^M去掉:
sed 's/^M$//g' func.txt
0at$the@begining^M
The#file#name#is#func,^M
9and%it's%suffix%is .txt
怎麼沒替換呢?
原來^為特殊字符,需要轉義
sed 's/\^M$//g' func.txt
0at$the@begining
The#file#name#is#func,
9and%it's%suffix%is .txt

6.下面將這些命令全部整合起來:
pg func.txt
0at$the@begining^M
The#file#name#is#func,^M
9and%it's%suffix%is .txt

at func.txt | sed 's/\$/ /g' | sed 's/@/ /g' | se 's/^[0-9]//g' | sed 's/\^M$//g' | sed 's/#/ /g' | sed 's/%/ /g'
at the begining
The file name is func,
and it's suffix is .txt

也可以將這些命令放在文件裡面:
pg func.sed
# !/bin/sed -f
# drop the "#"
s/#/ /g

# drop the number at the first of each line
s/^[0-9]//g

# drop the "$"
s/\$/ /g

# drop the "@"
s/@/ /g

# drop the "%"
s/%/ /g

# drop the "^M"
s/\^M//g

# EOF
執行命令:sed -f func.sed func.txt
at the begining
The file name is func,
and it's suffix is .txt

將執行過濾後的結果保存到sed.out文件中:
sed -f func.sed func.txt > sed.out
pg sed.out
at the begining
The file name is func,
and it's suffix is .txt

下面一個適用的例子
我從數據庫中查找的數據放在一個文件裡面:
pg sql.txt
LASTNAME SALARY
--------------- -----------
HAAS 152750.00
THOMPSON 94250.00

2 條記錄已選擇。

現在的需求是將其中的LASTNAME取出來,可以如下操作:
cat sql.txt | sed '/^--*/d' | sed '/^$/d' | sed '$d' | sed '1d' | awk '{print $1}'
取出其中的數字:
cat sql.txt | sed '1d' | sed '$d' | sed '/^$/d' | sed '/^--*/d' | awk '{print $2}'
152750.00
94250.00

在每行後面附加信息
pg info.txt
yeeXun
Linux
Aix
Unix
Windows

sed 's/[a-zA-Z]*/& -end-/g' info.txt
yeeXun -end-
Linux -end-
Aix -end-
Unix -end-
Windows -end-

在命令行給sed傳遞值,使用雙引號:
NAME="Scott in Oracle"
REPLACE="OUT"
echo $NAME | sed "s/in/$REPLACE/g"
Scott OUT Oracle

下面是一些行命令([]表示空格,[ ] 表示tab鍵)
-------------------------------------------------------------------
's/\.$//g' 刪除以.結尾的行
'-e /abcd/d' 刪除包含abcd的行
's/[][][]*/[]/g' 用一個空格替換多個空格
's/^[][]*//g' 刪除行首空格
's/\.[][]*/[]/g' 用一個空格替換.後面的多個空格
'/^$/d' 刪除空行
's/^.//g' 刪除行首的第一個字符
's/COL\(...\)//g' 刪除緊跟COL(的三個字符
's/^\///g' 從路勁中刪除第一個\
's/[ ]/[]//g' 用空格替代tab鍵
's/^[ ]//g' 刪除行首所有tab鍵
's/[ ]*//g' 刪除所有tab鍵
-------------------------------------------------------------------
Copyright © Linux教程網 All Rights Reserved