Awk输出格式

Awk输出格式,awk,gawk,Awk,Gawk,我有2.po文件,其中的一些单词有2种不同的含义 想用awk把它变成某种翻译器吗 例如 .po文件1中的 msgid“示例” msgstr“某物” .po文件2中的 msgid“示例” msgstr“某物” 我想到了这个 awk -F'"' 'match($2, /^example$/) {printf "%s", $2": ";getline; printf "%s", $2}' file1.po file2.po 输出将是 example:something example:somethi

我有2.po文件,其中的一些单词有2种不同的含义 想用awk把它变成某种翻译器吗

例如

.po文件1中的

msgid“示例”

msgstr“某物”

.po文件2中的

msgid“示例”

msgstr“某物”

我想到了这个

awk -F'"' 'match($2, /^example$/) {printf "%s", $2": ";getline; printf "%s", $2}' file1.po file2.po
输出将是

example:something example:somethinelse
我如何把它做成这种格式

example : something, somethingelse.
重新格式化

example:something example:somethinelse
进入

可以使用此一个衬里来完成:

awk -F":| " -v OFS="," '{printf "%s:", $1; for (i=1;i<=NF;i++) if (i % 2 == 0)printf("%s%s%s", ((i==2)?"":OFS), $i, ((i==NF)?"\n":""))}'
$ echo "example:something example:somethinelse example:something3 example:something4" | \
awk -F":| " -v OFS="," '{ \
printf "%s:", $1; \
for (i=1;i<=NF;i++) \
    if (i % 2 == 0) \
       printf("%s%s%s", ((i==2)?"":OFS), $i, ((i==NF)?"\n":""))}'
example:something,somethinelse,something3,something4
$ cat tst.awk
BEGIN{FS=":| ";OFS=","}      # define field sep and output field sep
{ printf "%s:", $1           # print header line "example:"
for (i=1;i<=NF;i++)          # loop over all fields
    if (i % 2 == 0)          # we're only interested in all "even" fields
        printf("%s%s%s", ((i==2)?"":OFS), $i, ((i==NF)?"\n":""))
}
把这个叫做:

awk -f tst.awk *.po

你能解释一下打印所有东西的代码吗?它工作得很好,但我不明白你是怎么做的。我想你是说一个一个?刚才添加了一些信息。是的,很抱歉,再次感谢您的时间:D
$ cat tst.awk
BEGIN{OFS=","}                               # set output field sep to ","
NF{                                          # if NF (i.e. number of fields) > 0 
                                             #   - to skip empty lines -
   if (match($0,/msgid "(.*)"/,a)) id=a[1]   # if line matches 'msgid "something", 
                                             #   set "id" to "something" 
   if (match($0,/msgstr "(.*)"/,b)) str=b[1] # same here for 'msgstr'
   if (id && str){                           # if both "id" and "str" are set
       r[id]=(id in r)?r[id] OFS str:str     # save "str" in array r with index "id".
                                             # if index "id" already exists, 
                                             #   add  "str" preceded by OFS (i.e. "," here) 
       id=str=0                              # after printing, reset "id" and "str"
   }
}
END { for (i in r) printf "%s : %s\n", i, r[i] } # print array "r"
awk -f tst.awk *.po
$ awk -F'"' 'NR%2{k=$2; next} NR==FNR{a[k]=$2; next} {print k" : "a[k]", "$2}' file1 file2
example : something, somethingelse