2013-07-09 56 views
3

我有文件test.txt使用正則表達式中的if語句

class c1 { 
    ___________ any text _____________ 
} 
class c2 { 
    ___________ any text _____________ 
} 
class c3 { 
    ___________ any text _____________ 
} 

我寫bash腳本掃描test.txt一行一行地比較正則表達式的每一行,以獲得包含類的頭線比較字符串,但不工作:(

#!/bin/bash 
while read line   
do   
    if [[ "$line" =~ "class *\w+" ]]; then 
     echo $line 
    fi 
done <test.txt 

最終目標每個類文件分開

+1

你的意思是在新文件中寫入每個類?通過分開檔案中的每個班級,你的意思是什麼? –

+1

@JS웃這是我的意思是寫每一類中的新文件 – Steve

回答

4

一種方式與awk

awk '/^class/{p=1;++x}/^}/{p=0;print $0>"file"x}p{print $0>"file"x}' test.txt 

輸出

$ head file* 
==> file1 <== 
class c1 { 
    ___________ any text _____________ 
} 

==> file2 <== 
class c2 { 
    ___________ any text _____________ 
} 

==> file3 <== 
class c3 { 
    ___________ any text _____________ 
} 
+1

我無法解釋我的謝意 – Steve

2

爲什麼不使用grep

kent$ grep -E '^class\s+\w+.*{' test 
class c1 { 
class c2 { 
class c3 { 
+1

如果我使用grep我不能繼續最終目標每類文件 – Steve

4

請嘗試遵循正則表達式。它採用字符clases,而不是字面空間和\w避免使用雙引號:

if [[ "$line" =~ class[[:blank:]][[:alnum:]]+ ]]; then 
    ... 
fi 

編輯:要寫入每個類到不同的文件,做類名的分組和重定向它:

#!/usr/bin/env bash 

while read line   
do  
    if [[ "$line" =~ class[[:blank:]]([[:alnum:]]+) ]]; then 
     echo "$line" >> ${BASH_REMATCH[1]}.txt 
    fi 
done <test.txt 

檢查結果,運行:

head c[123].txt 

國債收益率:

==> c1.txt <== 
class c1 { 

==> c2.txt <== 
class c2 { 

==> c3.txt <== 
class c3 { 
+1

分開謝謝 我可以寫正則表達式來表示 'CALSS C1 {' '___________ any text _____________' '}' – Steve

+0

@motaz:這是個問題嗎?你想排成一行嗎? – Birei

+1

我向你道歉 但最終的目標分開文件 中的每個類我可以在正則表達式嗎? – Steve

3

特殊的正則表達式字符必須是加引號(手冊上說「模式的任何部分可以被引用,以迫使它匹配的字符串。」

此外,bash正則表達式不理解perl \w

這工作:

[[ $line =~ "class "[[:alnum:]_]+ ]]