gpt4 book ai didi

linux - 在 Shell 脚本中读取 CSV 文件,直到没有标题的行尾

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:38 29 4
gpt4 key购买 nike

我有一个名为“readfile.csv”的文件,其中包含以下内容。

Name    Id        VAl       Number    IP
James,007,$500,111-111-111,111-000-000
Bond,700,$900,100-000-999, 666-999-000

此处 Name、Id、Val、Number 和 IP 是 csv 文件中的标题,第二行即 FirstVal、SecondVal 等是这些标题的值。我只想读取值而不是标题并将其显示在控制台中。我该怎么做?而且我还想读取值直到行尾/文件末尾,因为我不知道文件中可以存在多少列。它可以是 5 或 6 列。

现在我可以在 shell 脚本中读取没有标题的单行,如下所示。但这对我这里提到的情况没有帮助。

#!/bin/bash

val1=( $(cut -d ',' -f1 readfile.csv ) )
printf "%s\n" "${val1[0]}"
val2=( $(cut -d ',' -f2 readfile.csv ) )
printf "%s\n" "${val2[0]}"
val3=( $(cut -d ',' -f3 readfile.csv ) )
printf "%s\n" "${val3[0]}"

我实际上想将这些值附加到其他脚本。例如,我有一个名为 runfile.sh 的脚本,它附加来自 awk 的值并通过 http 打开一个文件位置。

例如,'runfile.sh' 正在存储这个值:

'https://my_win_loc/personinfo'

现在 runfile 将读取 csv 文件并将每个值附加到此 url,如下所示:

'https://my_win_loc/personinfo/James'
'https://my_win_loc/personinfo/Bond'

请帮我解决这个问题。提前致谢。

最佳答案

通常,这类事情是通过 awk 或简单的 read 循环完成的。

#!/bin/bash

exec < readfile.csv || exit 1
read header # read (and ignore) the first line
while IFS=, read name id val number ip; do
echo name = "$name"
echo id = "$id"
echo val = "$val"
echo number = "$number"
test -n "$ip" && echo ip = "$ip"
done

关于linux - 在 Shell 脚本中读取 CSV 文件,直到没有标题的行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976841/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com