2016-05-23 37 views
-1

我必須製作正則表達式才能匹配一個數字。 它應該匹配7和a7b,但不是77. 我做到了這一點,但它似乎在sed中不起作用。僅匹配單個數字sed

(?<![\d])(?<![\S])[1](?![^\s.,?!])(?!^[\d]) 
(?<![\d])(?<!^[\a-z])\d(?![^a-z])(?!^[\d]) 

我在做什麼錯?

編輯:

我需要更換與只有1位數的號碼,如

sed 's/regex/@/g' file //regex to match "1" 

文件內容

1 2 3 4 5 11 1 
agdse1tg1xw 
6 97 45 12 

應該成爲

@ 2 3 4 5 11 @ 
[email protected]@xw 
6 97 45 12 
+0

的sed只支持BRE和ERE。但是你可以使用'grep -oP'或'grep -P'來使用PCRE。 – andlrc

+1

爲什麼你的例子中的2,3,4,5和6不會被轉換成'@'s?你想轉換1位數字還是數字1? –

+0

編輯已經使這個問題不清楚。 – sjsam

回答

0

要你在你的問題的例子顯示的是:

$ sed -r 's/(^|[^0-9])1([^0-9]|$)/\[email protected]\2/g' file 
@ 2 3 4 5 11 @ 
[email protected]@xw 
6 97 45 12 

但這隻適用於您的數據中沒有1 1。如果你做了你需要2遍:

$ echo '1 1' | sed -r 's/(^|[^0-9])[0-9]([^0-9]|$)/\[email protected]\2/g' 
@ 1 

$ echo '1 1' | sed -r 's/(^|[^0-9])[0-9]([^0-9]|$)/\[email protected]\2/g; s/(^|[^0-9])[0-9]([^0-9]|$)/\[email protected]\2/g' 
@ @ 

,如果你想要做的是,對於任何單個數字將是:

$ sed -r 's/(^|[^0-9])[0-9]([^0-9]|$)/\[email protected]\2/g; s/(^|[^0-9])[0-9]([^0-9]|$)/\[email protected]\2/g' file 
@ @ @ @ @ 11 @ 
[email protected]@xw 
@ 97 45 12 
+1

這是我正在尋找。謝謝! –

0

輸入

a77 
a7b 
2ab 
882 
9 
abcfg9 
9fg 
ab9 

腳本

sed -En '/^[^[:digit:]]*[[:digit:]]{1}[^[:digit:]]*$/p' filename 

輸出

a7b 
2ab 
9 
abcfg9 
9fg 
ab9 
+0

值得一提的是,你應該在OSX上使用'-E',並且GNU sed也應該支持'-E',即使它沒有在'man sed'中提到。 – andlrc

+0

'*'會使兩個數字都可選匹配'77' – rock321987

+0

單個數字與此模式不匹配。 – SLePort

0

的sed只支持BREERE,但可以啓用PCREgrep -P

% printf 'a77\na7b\n2ab\n82\n' | grep -P '(?<!\d)\d(?!\d)' 
a7b 
2ab 

的grep會證明打印匹配行,但有一個選項,只打印匹配:

% printf 'a77\na7b\n2ab\n82\n' | grep -oP '(?<!\d)\d(?!\d)' 
7 
2 
+0

這是我需要的,但它有點必須與sed,因爲我必須替換數字 –

+0

@Restal你覺得如何添加Perl到你的依賴項:'perl -pe s /(?<!\ d)\ d(?\ d)/ replacement/g input_file' – andlrc

+0

不幸的是不能接受,因爲我必須使用sed –