使用Shell脚本格式化文件内容 [英] format a file content using shell script
问题描述
大家好,我是shell编码的初学者.每天我需要将文件的数据转换为另一种格式,通常我会使用文本编辑器"手动进行操作.但是我经常犯错.因此,我决定编写一个简单的脚本来为我完成工作.文件内容是这样的
Hello everyone I'm a beginner in shell coding. In daily basis I need to convert a file's data to another format, I usually do it manually with Text Editor. But I often do mistakes. So I decided to code an easy script who can do the work for me. The file's content like this
/release201209
a1,a2,"a3",a4,a5
b1,b2,"b3",b4,b5
c1,c2,"c3",c4,c5
对此:
a2>a3
b2>b3
c2>c3
脚本应忽略第一行,并打印第二个和第三个值,并用'>'分隔我到了一半,这是我的代码
The script should ignore the first line and print the second and third values separated by '>' I'm half way there, and here is my code
#!/bin/bash
cat $1 | sed '1d' | cut -d, -f2-3 | tr -d '"' > $2
它一直运行良好,直到我发现它不适用于a3这样包含逗号的数据类型: data,VERSION,"FUNDS.TRANSFER,ASS.VERS.TIERS.BOP",
哪个返回 VERSION> FUNDS.TRANSFER
代替 VERSION> FUNDS.TRANSFER,ASS.VERS.TIERS.BOP
It was working well until I found out that it is not working for a type of data containing comma in a3 like this one:
data,VERSION,"FUNDS.TRANSFER,ASS.VERS.TIERS.BOP",,
Which returns
VERSION>FUNDS.TRANSFER
instead of
VERSION>FUNDS.TRANSFER,ASS.VERS.TIERS.BOP
您能帮我更新一下吗?谢谢
Can you help me out updating it please ? Thanks
推荐答案
考虑使用适当的CSV解析工具(例如 csvtool
)提取相关列(比推出您的列更容易,更可靠)自己解析).然后,使用 tr
/ sed
进行必要的转换:
Consider using a proper CSV parsing tool like csvtool
to extract the relevant columns (its much easier & more reliable than rolling out your own parsing). Then, use tr
/sed
to do the necessary transformations:
sed '1d' file.txt | csvtool -t ',' col 2,3 - | tr -d '"' | sed 's/,/>/'
步骤:
- 使用
sed
删除标题行 - 使用
csvtool
提取第二列和第三列 - 使用
tr
删除双引号 - 使用
sed
将 first>
(您不能使用tr
,因为这会进行全局翻译)
- Remove the header line using
sed
- Use
csvtool
to extract the 2nd and 3rd columns - Use
tr
to remove the double quotes - Use
sed
to map the first,
to a>
(you can't usetr
for this since that does a global translation)
您可以使用包管理器安装 csvtool
,例如在基于Debian的系统上 sudo apt-get install csvtool
.将 apt-get
替换为其他系统上的软件包管理器,例如 yum
, brew
,...
You can install csvtool
with your package manager, e.g. on a Debian-based system sudo apt-get install csvtool
. Replace apt-get
with your package manager on other systems e.g. yum
, brew
, ...
这篇关于使用Shell脚本格式化文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!