linux - 如何用bash脚本替换字符串并写回结果

标签 linux bash csv

有一个 CSV 文件,其中包含一些列,第一列是 5 位客户编号,其他列以“;”分隔。

这是一个例子:

12345;some;other;cols;comes;here
;some;other;cols;comes;here
;some;other;cols;comes;here
67890;some;other;cols;comes;here
34567;some;other;cols;comes;here
;some;other;cols;comes;here
;some;other;cols;comes;here
;some;other;cols;comes;here
;some;other;cols;comes;here
24315;some;other;cols;comes;here

如果第一列为空,那么我需要设置最后一个给定的客户 ID。结果应如下所示:

12345;some;other;cols;comes;here
12345;some;other;cols;comes;here
12345;some;other;cols;comes;here
67890;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
24315;some;other;cols;comes;here

现在我用 bash 脚本逐行读取文件,并想检查该行是否以数字开头。如果是,则用“;”分解该行并使用 array[0] (第一个值)设置 customerID。接下来,我检查该行是否不以数字开头,并希望在该行的开头写入五位数字。但我无法使用客户 ID 访问数组索引。

这是我的脚本:

#!/bin/bash
while read line
do
    row=$line
    if echo $row |grep "^[0-9].*$" > /dev/null;
      then
        arr=$(echo $row | tr ";" "\n")
        echo ${arr[0]};
    fi
done < $1

我得到了没有“;”的整行内容而不是将 CustomerID 作为 arr[0] 接下来我不知道如何将行开头的数字写回到文件中。有人可以帮助我吗?

最佳答案

尝试:

awk -v id=12345 -F ';' '$1==""{$1=id;} {id=$1; print}'  OFS=';' file
  • awk 使用字段分隔符 ;,这使您可以以 $1$2$3 等形式访问每个单独的字段.
  • -v id=12345 是传递给 awk 的命令行参数,以便在第一个字段为空时使用
  • $1="" 是检查第一个字段是否为空的条件
  • $1=id 正在将 $1 设置为传递的变量 id
  • {id=$1; print} 设置用于下一行的 id 变量,然后打印该行

输出:

12345;some;other;cols;comes;here
12345;some;other;cols;comes;here
12345;some;other;cols;comes;here
67890;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
34567;some;other;cols;comes;here
24315;some;other;cols;comes;here

关于linux - 如何用bash脚本替换字符串并写回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19679932/

相关文章:

python - 在 2 个制表符分隔的文本文件中搜索和编辑值 python 3

linux - 从 Win7 连接到 Linux VirtualBox 中的 PostgreSql 数据库

linux - 在 Ubuntu 上导航到/ect

csv - Athena 无法使用 OpenCSVSerde 解析日期

java - 在 Linux 2.6 系统上安装多个 Java 导致 'Command not found' 错误

bash - expr : non-integer argument. 如何减去点十进制数

mysql - 将 CSV 文件导入 MySql 表,其中一列作为 CSV 文件的名称

linux - 在 bash 中使用 for 循环检查数组元素是否为空

linux - 无法将 bool 值分配给 bash 中的变量?

linux - 这行在 shell 脚本中有什么作用?