我有一个文本文件,我将链接格式化为
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>
答案 0 :(得分: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 :(得分:1)
您的文字档案:
nampt@nampt-desktop:/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
输出
nampt@nampt-desktop:/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>
答案 2 :(得分: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或类似的