如何使用 bash 将 txt 文件中的每行多个字符串值转换为 csv

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

应该是我有以下 txt 文件的内容,例如

输入.txt
简·无名
20
美国
约翰·史密斯
21
美国

我想要的输出是

输出.csv
姓名、年龄、国家
Jane Doe,20 岁,美国
约翰·史密斯,21 岁,美国

我已经使用 powershell 实现了这一点,但我想坚持使用 bash 的要求。

linux bash shell scripting
1个回答
0
投票

您可以使用简单的

awk
命令来实现此目的:

input="input.txt"
output="output.csv"

# Write the header separately to the output file
echo "Name,Age,Country" > $output

awk '{
    if (NR % 3 == 1) {
        name = $0
    } else if (NR % 3 == 2) {
        age = $0
    } else {
        country = $0
        print name "," age "," country
    }
}' $input >> $output

示例演示

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.