2016-07-05 59 views
1

我有我出口鏈接格式如下轉換文本文件到XML文件(標題&& URL)

Cover-ups http://example.com/1 
One-pieces http://example.com/2 
Sarongs http://example.com/3 

如何使用一個awk命令或類似的東西,像這樣以格式化的文本文件

<link> 
    <title>Cover-ups</title> 
    <url>http://example.com/1</url> 
</link> 

<link> 
    <title>One-pieces</title> 
    <url>http://example.com/2</url> 
</link> 

<link> 
    <title>Sarongs</title> 
    <url>http://example.com/3</url> 
</link> 

回答

1

看一看:

把數據變成XML

http://www.mailsend-online.com/blog/converting-data-to-xml-with-awk.html

這應該讓你開始:

BEGIN { 
    FS="|"; 
    printf("<?xml version=\"1.0\" ?>\n"); 
} 

NF==1 { 
    printf("<link>\n"); 
    split($1, a, " "); for (i in a) { 
    if (i == 1) 
     printf("<url>%s</url>\n", a[2]); 
    if (i == 2) 
     printf("<title>%s</title>\n", a[1]); 
    } 
    printf("</link>\n"); 
} 

END { 
} 

輸出:

<?xml version="1.0" ?> 
<link> 
    <title>Cover-ups</title> 
    <url>http://example.com/1</url> 
</link> 
<link> 
    <title>One-pieces</title> 
    <url>http://example.com/2</url> 
</link> 
<link> 
    <title>Sarongs</title> 
    <url>http://example.com/3</url> 
</link> 
+1

我最終得到我自己的解決方案感謝您鏈接的文檔非常感謝。請重新編輯它,如果你有機會 – NooBskie

+0

@gotnull,將FS更改爲|並使用默認的FS分手手段不是很明確... ... - – JJoao

1

您的文本文件:

[email protected]:/mnt$ cat 1 
Cover-ups http://example.com/1 
One-pieces http://example.com/2 
Sarongs http://example.com/3 

我的shell腳本:

#!/bin/sh 
while read line 
do 
tmp1=$(echo $line|awk '{print $1}') 
tmp2=$(echo $line|awk '{print $2}') 

cat >> output << EOF 
<link> 
    <title>${tmp1}</title> 
    <url>${tmp2}</url> 
</link> 

EOF 
done < 1 

輸出

[email protected]:/mnt$ cat output 

<link> 
    <title>Cover-ups</title> 
    <url>http://example.com/1</url> 
</link> 

<link> 
    <title>One-pieces</title> 
    <url>http://example.com/2</url> 
</link> 

<link> 
    <title>Sarongs</title> 
    <url>http://example.com/3</url> 
</link> 
0

1:又一個awk中oneliner:

awk '{printf "<link>\n<title>%s</title>\n<url>%s</url>\n</link>\n\n",$1,$2}' 

2:在我用以下awk中哲學Perl版本類似的情況(此時生成有效的XML)

#!/usr/bin/perl -na 

use XML::Writer::Simple tags => [qw/refs link title url/], partial=>1 ; 

BEGIN{ print xml_header,start_refs; } 
    { print link(title($F[0]),url($F[1])),"\n";} 
END { print end_refs; } 

生產:

$perl links2xml mylinks 

<?xml version="1.0"?> 
<refs> 
<link><title>Cover-ups</title><url>http://example.com/1</url></link> 
<link><title>One-pieces</title><url>http://example.com/2</url></link> 
<link><title>Sarongs</title><url>http://example.com/3</url></link> 
</refs> 

選項-na令Perl的行爲模式在awk方式( while(line=<>){F=split(line); BODY}

如果需要使用CPAN(sudo cpan XML::Writer::Simple)安裝模塊,apt-get或者類似