簡體   English   中英

文本格式-sed,awk,shell

[英]Text formating - sed, awk, shell

我需要一些幫助,以嘗試使用文件中的排除項列表來構建變量。

所以我有一個用於rsync的排除文件,看起來像這樣:

*.log
*.out
*.csv
logs
shared
tracing
jdk*
8.6_Code
rpsupport
dbarchive
inarchive
comms
PR116PICL
**/lost+found*/
dlxwhsr*
regression
tmp
working
investigation
Investigation
dcsserver_weblogic_
dcswebrdtEAR_weblogic_

我需要構建一個字符串用作變量以供輸入egrep -v,以便可以像從find -ls中使用egrep -v時一樣對rsync使用相同的排除列表。

因此,到目前為止,我已經創建了此代碼,以刪除所有的“ *”和“ /”-然后在看到某些特殊字符時將其轉義:

cat exclude-list.supt | while read line
    do
    echo $line | sed 's/\*//g' | sed 's/\///g' | 's/\([.-+_]\)/\\\1/g'

我也需要輸出,如下所示,然后將其導出為變量:

SEXCLUDE_supt="\.log|\.out|\.csv|logs|shared|PR116PICL|tracing|lost\+found|jdk|8\.6\_Code|rpsupport|dbarchive|inarchive|comms|dlxwhsr|regression|tmp|working|investigation|Investigation|dcsserver\_weblogic\_|dcswebrdtEAR\_weblogic\_"

有人可以幫忙嗎?

以下問題:

cat exclude-list.supt | while read line
    do
    echo $line | sed 's/\*//g' | sed 's/\///g' | 's/\([.-+_]\)/\\\1/g'

Sed逐行讀取文件,因此cat | while read line;do echo $line | sed cat | while read line;do echo $line | sed cat | while read line;do echo $line | sed是完全冗余的,而且sed可以通過將它們作為逗號分隔的列表傳遞或使用-e選項來進行多次替換,因此管道傳輸sed三次的次數太多了。 '[.- + _]'的問題是-之間. +因此在字符類中使用-時,它會被解釋為范圍.-+ 。將其放在開頭或結尾的末尾會失去[._+-]類的含義。

更好的方法:

$ sed -e 's/[*/]//g' -e 's/\([._+-]\)/\\\1/g' file
\.log
\.out
\.csv
logs
shared
tracing
jdk
8\.6\_Code
rpsupport
dbarchive
inarchive
comms
PR116PICL
lost\+found
dlxwhsr
regression
tmp
working
investigation
Investigation
dcsserver\_weblogic\_
dcswebrdtEAR\_weblogic\_

現在我們可以通過tr '\\n' '|' 用管道替換換行符,以便為egrep准備備用:

$ sed -e 's/[*/]//g' -e 's/\([._+-]\)/\\\1/g' file | tr "\n" "|"
\.log|\.out|\.csv|logs|shared|tracing|jdk|8\.6\_Code|rpsupport|dbarchive|...

$ EXCLUDE=$(sed -e 's/[*/]//g' -e 's/\([._+-]\)/\\\1/g' file | tr "\n" "|")

$ echo $EXCLUDE
\.log|\.out|\.csv|logs|shared|tracing|jdk|8\.6\_Code|rpsupport|dbarchive|...

注意:如果文件以換行符結尾,則需要刪除最后的尾部| ,請嘗試sed 's/\\(.*\\)|/\\1/'

這可能對您有用(GNU sed):

SEXCLUDE_supt=$(sed '1h;1!H;$!d;g;s/[*\/]//g;s/\([.-+_]\)/\\\1/g;s/\n/|/g' file)

這應該可以,但是我想有更好的解決方案。 首先將所有內容存儲在bash數組中:

SEXCLUDE_supt=$( sed -e 's/\*//g' -e 's/\///g' -e 's/\([.-+_]\)/\\\1/g' exclude-list.supt)

然后再次處理它以替換空白:

SEXCLUDE_supt=$(echo $SEXCLUDE_supt |sed 's/\s/|/g')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM