在 bash 中用 sed 替换回车符(按 CTRL+V 出现的^M)

问题描述 投票:0回答:1

我正在尝试在 bash 中管理 csv 格式的文件 .xlsx。

我将 Excel 文件 (.xlsx) 转换为 .csv (CSV UTF-8(逗号分隔)) 以开始管理列。

但是,我注意到 Excel 文件(.xlsx)中的信息包含在列换行符的单元格中( ).

你能帮忙解决这个问题吗?

The way it look at vim the converted file from xlsx to csv

The information it's not shown properly due to a problems in the segmentation of columns

在图像中我应用的命令之前是:cat file | awk -F '|' '{打印$2"|"$7"|"$27"|"$29"|"$30"|"$31}'

  • 我确实认为解决方案是使用 sed 来消除 使用以下命令: sed ':a;N;$!ba;s/ //g'文件 如何替换每个换行符( )使用 sed 带有空格? 然后我可以替换回车符 (^M) (例如| sed -e 's/^M/ /g') 使用 awk 正确管理每一列(例如 input | awk -F '|' '{print $2"|"$7"|"$27"|"$29"|"$30"|"$31}')

    但是,我认为该解决方案不起作用,因为通过应用第一个 sed 命令,所有信息都保留在同一行中,然后我无法使用 awk 命令来管理它。

你有想过其他的解决办法吗?

The csv file after applying sed ':a;N;$!ba;s/\n/ /g'

我的期望是如图所示 The info of each line be with \n to be able to manage with awk each column The result I expect is as shown here by applying the awk command

bash csv awk sed
1个回答
0
投票

要将行末尾的 CR-LF 转换为 LF 并删除字段中的 LF,这应该使用任何 awk 并假设您的文件足够小以适合内存:

awk '
    {
        sub(/\r$/,"")
        rec = rec $0 ORS
    }
    END {
        FS = OFS = "\""
        $0 = rec
        for ( i=2; i<=NF; i+=2 ) {
            gsub(/\n/," ",$i)
        }
        printf "%s", $0
    }
' file

它未经测试,因为您的问题中没有文本示例输入/输出。

© www.soinside.com 2019 - 2024. All rights reserved.