有一个 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/