2017-08-24 316 views
1

我有一個看起來像匹配使用grep並打印匹配的模式多種模式

..<long-text>..."field1":"some-value"...<long-text>...."field2":"some-value"... 
..<long-text>..."field1":"some-value"...<long-text>...."field2":"some-value"... 
..<long-text>..."field1":"some-value"...<long-text>...."field2":"some-value"... 

我想從在bash文件的每一行中提取出來field1field2文件。我希望field1和field2出現在每行的同一行中。所以輸出應該喜歡 -

"field1":"some-value" "field2":"some-value" 
"field1":"some-value" "field2":"some-value" 
"field1":"some-value" "field2":"some-value" 

我寫了一個grep的表情像 -

grep -E '"field1":"[a-z]*".*"field2":"[a-z]*"' -o 

但由於.*之間,它產生這兩個表達式之間所有的所有文本。我也試過

grep -E '"field1":"[a-z]*"|"field2":"[a-z]*"' -o 

但是,這會輸出所有field1s在單獨的行,然後在單獨的行中輸出所有field2s。

如何獲得預期的輸出?

回答

4

您可以使用grepawk來格式化結果:

grep -oE '"(field1|field2)":"[^"]*"' file | awk 'NR%2{p=$0; next} {print p, $0}' 

"field1":"some-value" "field2":"some-value" 
"field1":"some-value" "field2":"some-value" 
"field1":"some-value" "field2":"some-value" 
0

使用sed

echo abcdef | sed 's/\(.\).*\(.\)/\1\2/' 
# yields: af 

您的具體情況:

sed 's/.*\("field1":"[a-z]*"\).*\("field2":"[a-z]*"\).*/\1 \2/' yourfile 

如果某些行不匹配的話,那麼做你grep第一,例如,

grep -Eo '"field1":"[a-z]*".*"field2":"[a-z]*"' yourfile | 
    sed 's/.*\("field1":"[a-z]*"\).*\("field2":"[a-z]*"\).*/\1 \2/'