在bash中修剪字符串中的换行符

时间:2014-10-02 21:21:07

标签: excel bash csv sed

我从excel导出的.csv文件中提取数据。

csv文件如下所示:

Category,Feature,Description,app1,app2,app3,app4,app5,app6,app7
Employee Relations,Employee Management,,y,y,n,y,y,y,n
Employee Relations,Employee Availability,,y,y,n,n,y,y,n

问题是结束字符换行正在阻碍。请使用以下代码:

title=$(head -n 1 $1) # grab the first row
title=`echo $title | sed -e 's/^ *//' -e 's/ *$//'` # me trying to fix. I think this is the issue
echo $title  #this seems to look right
IFS=',' read -a titline <<<"$title"   # make it an array

for (( i = 0 ; i < ${#titline[@]} ; i++ )) do
    echo "[[${titline[$i]}]]"
done

打印出来:

Category,Feature,Description,app1,app2,app3,app4,app5,app6,app7
[[Category]]
[[Feature]]
[[Description]]
[[app1]]
[[app2]]
[[app3]]
[[app4]]
[[app5]]
[[app6]]
]]app7

你可以看到最后一行应该是:

[[app7]]

这与其他剧本紧密相关 我不确定我做错了什么,可以使用指针

1 个答案:

答案 0 :(得分:2)

问题是你的csv文件有DOS行结尾。

我复制并粘贴了您的数据和脚本,并生成了输出:

Category,Feature,Description,app1,app2,app3,app4,app5,app6,app7
[[Category]]
[[Feature]]
[[Description]]
[[app1]]
[[app2]]
[[app3]]
[[app4]]
[[app5]]
[[app6]]
[[app7]]

然后我将csv文件转换为DOS行结尾并得到了你看到的相同问题。

解决方法是在读取文件之前使用dos2unix或类似的实用程序来修复文件。这可以按如下方式完成:

title=$(dos2unix <"$1" | head -n 1) # grab the first row
echo $title
IFS=',' read -a titline <<<"$title"   # make it an array
for (( i = 0 ; i < ${#titline[@]} ; i++ )) do
    echo "[[${titline[$i]}]]"
done

或者,您可以使用sed

title=$(head -n 1 "$1" | sed 's/\r//') # grab the first row
echo $title
IFS=',' read -a titline <<<"$title"   # make it an array
for (( i = 0 ; i < ${#titline[@]} ; i++ )) do
    echo "[[${titline[$i]}]]"
done