【问题标题】:How do I use the value of a column in a csv to determine value of another column in the same csv using bash?如何使用 csv 中的列的值来使用 bash 确定同一 csv 中另一列的值?
【发布时间】:2017-08-22 02:53:24
【问题描述】:

我有一个包含我想要更新的数据库信息的大型 csv。

我想使用电子邮件列(第 1 列)中的值来确定分段列(第 4 列)的值。

例如,如果电子邮件包含“nhs.net”,则分段列应为“健康 - NHS”。

当前段列显示“未知专业”,我不确定如何根据另一列中的值是否为真,使用 bash 覆盖该值。

示例

zoe.russell@nhs.net, zoe, russell, 未知专业

会变成:

zoe.russell@nhs.net, zoe, russell, 健康 - NHS

到目前为止,我有这个......(我的第一个 bash 脚本,以及这里的第一个 q)

#!/bin/bash

echo 'enter the email domain you are searching for in the email field'
read email 
echo 'please enter the file you wish to search'
read file
echo 'ok looking for' $email 'in' $file
echo ...
# cat $file | grep -E -i $email

x=$(cat $file | grep -E -i $email | wc -l)
echo 'ok' $x 'email address were found in' $file
echo 'here is a sample of the first 10 lines in the segment column' 
cat us.tmp | cut -d ',' -f10 | head -10 

echo 'please enter the segment name you want to replace these with'
read new
echo value will be replaced with $new

【问题讨论】:

  • 段列(第 3 列) - 实际上,它在第 4 列

标签: bash csv awk sed grep


【解决方案1】:

根据您的要求,您可以使用下面的 awk -

$cat file
zoe.russell@nhs.net, zoe, russell, Unknown Specialism

$awk -F, '{if($1 ~ /nhs.net/) {$4=" Health - NHS"}; print $0}' OFS=, f
zoe.russell@nhs.net, zoe, russell, Health - NHS

【讨论】:

    【解决方案2】:

    在 awk 中使用另一个文件进行段列替换:

    $ cat repl.txt
    nhs.net, Health - NHS
    

    代码:

    $ awk '
    BEGIN { FS=OFS="," }                            # delimiters are: ,
    NR==FNR { a[$1]=$2; next }                      # read replacements in a hash
    split($1,t,"@") && (t[2] in a) {                # get the domain name and use is 
        $NF=a[t[2]]                                 # as reference to a hash
    }
    1' repl.txt file                                # 1 is the print command
    zoe.russell@nhs.net, zoe, russell, Health - NHS
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 2013-04-12
      • 1970-01-01
      • 2021-10-15
      • 2021-06-08
      • 1970-01-01
      相关资源
      最近更新 更多