2011-04-26 42 views
2

我在格式的字符串`富=「是一個第一個」 foo1 =「是的第二個」 foo3 =「是第三個」和許多領域,如所述圖案。我想解析這個和O/P爲要分析在外殼腳本中的字符串

foo    foo1    foo3 
is a first one is a second one is a third one 

任何幫助,非常感謝。

+0

你有什麼已經嘗試過?你在哪裏已經研究過這個任務?你有沒有遇到任何問題? – 2011-04-26 05:43:12

+0

我使用FS commadn試圖與AWK但沒有贏得成功 – suresh 2011-04-26 07:14:26

+0

既然你已經嘗試過'awk',我建議你移動到perl,而不是在外殼做到這一點。那裏很簡單。 – 2011-04-26 08:11:06

回答

0

這是你想要的?

sed -nr 's/" /"\n/g;s/=/\n/gp' <<END 
    > foo="is a first one" foo1="is a second one" foo3="is a third one" 
    > END 
    foo 
    "is a first one" 
    foo1 
    "is a second one" 
    foo3 
    "is a third one" 
+0

非常感謝您的回覆。它工作正常。請你給我解釋一下它是如何工作的,我也希望命令從文件中讀取輸入。你能否相應地糾正它。如果我可以以表格形式打印數據而不是按行打印,那將會很好。 – suresh 2011-04-26 08:54:54

+0

我很抱歉回覆太遲了,但我認爲你必須得到更好的答案... – xiaofengmanlou 2011-05-09 14:44:16

2

對輸出進行分欄是很難的部分。 (在這裏我會同意Noufal的說法,perl是一個很好的選擇。)但是,它可以與其他更基本的工具一起使用。例如:

 
$ cat input 
foo 
is a first one 
foo1 
is a second one 
foo3 
is a third one 
$ (awk 'NR % 2' input; awk 'NR % 2 == 0' input) | paste - - - | column -s' ' -t 
foo    foo1    foo3 
is a first one is a second one is a third one 

(請注意,-s參數欄應包含單引號之間的選項卡。)

1

AWK是非常細做字符串解析。

s='foo="is a first one" foo1="is a second one" foo3="is a third one"' 
echo $s | awk 'BEGIN{ 
    FS="\042 " 
} 
{ 
    c=NF 
    for(i=1;i<=NF;i++){ 
     m = split($i , a, "=") 
     header[i] = a[1] 
     content[i]= a[2] 
    } 
} 
END{ 
    for(i=1;i<=c;i++){ 
     printf "%s\t", header[i] 
    } 
    print "" 
    for(i=1;i<=c;i++){ 
     printf "%s\t", content[i] 
    } 
    print "" 
} 
' 
0

盜竊William's answer使用column,這種接受OP的建議的輸入。它需要將雙引號作爲樣品每輸入值:

s='foo="is a first one" foo1="is a second one" foo3="is a third one"' 
echo "$s" | awk -F'"' ' 
    { 
    for (i=1; i<=NF; i+=2) { 
     sub(/^[[:space:]]*/, "", $i) 
     sub(/=$/, "", $i) 
     vars=vars $i "\t" 
    } 
    for (i=2; i<=NF; i+=2) {vals=vals $i "\t"} 
    } 
    END {print vars; print vals} 
' | column -t -s $'\t' 

輸出

foo    foo1    foo3 
is a first one is a second one is a third one