Shell擷取文字一段區間的方法

2021-09-29 01:08:27 字數 4662 閱讀 8037

假設有一段日誌,我需要擷取2019/09/232019/09/29之間期間的日誌。

那麼,我利用shell怎麼去擷取呢

實現方法

sed -n '/^2019\/09\/23/,/2019\/09\/29/p' log.txt

sed -n '/^a/,/bp/'  file
這個就是擷取a和b之間的字元,包括a和b為什麼在a前面加上乙個^這個是乙個正則,表示從a開頭開始匹配

以上的結果為:

接下來,可以過濾2019/09/232019/09/29

sed -n '/^2019\/09\/23/,/2019\/09\/29/p' log.txt | grep -ev '(^2019\/09\/23 |2019\/09\/29)'
用grep過濾即可 grep -e 表示過濾帶有正規表示式的內容 -v 表示不顯示

結果為:

[root@aliyun test]# sed -n '/^2019\/09\/23/,/2019\/09\/29/p' log.txt | grep -ev '(^2019\/09\/23 |2019\/09\/29)'

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

2019/09/25 12:41:35 [warn] 10#10: could not build optimal proxy_hea

[root@aliyun test]#

正是我想要的內容

Shell擷取文字一段區間的方法

假設檔案 text.txt 內容如下 xx yyyyyyyyyyyyyyyy zzzzzzzzzzzzzzzzzzz start mark 10 aaaaa bbbb cccc 20 aaaaa bbbb cccc 30 aaaaa bbbb cccc 40 aaaaa bbbb cccc yyyy...

String擷取一段

1.若知道要從第幾個位置開始擷取,可以直接選用substring 方法 2.若不知道要從哪邊開始擷取,但是知道string中要從哪段開始,只是要中間一段字串 如 string str age 20 address sz name mason int begin str.indexof address...

一段部署shell

一段部署shell usr bin env bash 目標伺服器ip host 1 目標伺服器端口 port 225 部署目錄 deploy dir 2 環境 env 3 備份目錄 bak dir deploy bak bak file api date y m d h m s tar.gz run...