将输出转换为 csv 格式 Linux

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

我创建了一个脚本,该脚本从名为 command from the script 的命令生成此输出:

#Name  age  number       address
mark  23   89756342192   Paris 23=rue

我会把它转换成用

;

分隔的csv格式
#Name;age;number;address
mark;23;89756342192;Paris 23=rue

剧本

#!/bin/bash

# Generate the input file using the command and capture its output
if ! the command | awk '{print $1,$2,$3,$4,$5}' > input.txt; then
    echo "Failed to generate input file: $(hset --display --argument pvg 2>&1)"
    echo "####<inc1000>" > output.csv
    echo "#Error: Failed to generate input file" >> output.csv
    echo "####</inc1000>" >> output.csv
    exit 1
fi

# Convert the input file to CSV format
if ! awk 'BEGIN{OFS=";";print "#Resource","Attribute","System","value"}{print $1,$2,$3,$4,$5}' input.txt > output.csv; then
    echo "Failed to convert input file to CSV format"
    echo "####<inc1000>" > output.csv
    echo "#Error: Failed to convert input file to CSV format" >> output.csv
    echo "####</inc1000>" >> output.csv
    exit 1
fi

# Add start and end markers to output file
echo "####<inc1000>" | cat - output.csv > temp && mv temp output.csv
echo "####</inc1000>" >> output.csv

echo "Conversion successful"

我有一个标题生成两次的问题

####</inc1000>
#Name;age;number;address
#Name;age;number;address;
mark;23;89756342192;Paris;23=rue
####</inc1000>

我会编辑它只获得一次标题

#Name;age;number;address

linux bash shell
1个回答
0
投票

我认为你想得太多了……只有当你有语法错误时awk才会失败——因此在开发过程中只会失败几次。在那之后测试转换失败似乎非常不必要。

剩下的可以浓缩为:

command | awk 'BEGIN{OFS=";";print "####<inc1000>"}{$1=$1;print}END{print "####</inc1000>"}' > output.csv ||
(echo "Failed to generate input file: $(hset --display --argument pvg 2>&1)"
 echo "####<inc1000>" > output.csv
 echo "#Error: Failed to generate input file" >> output.csv
 echo "####</inc1000>" >> output.csv)
© www.soinside.com 2019 - 2024. All rights reserved.