我是bash脚本的初学者,并且我已经尝试解决了8个多小时。 我已经搜索了StackOwerflow并尝试了满足我的需求的答案,但是没有成功。
我想使用bash脚本将csv文件的日期值更改为当前日期。
我正在使用虚拟.csv文件(http://eforexcel.com/wp/wp-content/uploads/2017/07/100-Sales-Records.zip),并且想要将第6个值(日期)更改为当前日期。
到目前为止,我一直在做什么: 我创建了一行csv来测试脚本
cat oneline.csv:
澳大利亚和大洋洲,图瓦卢,婴儿食品,离线,H,5/28 / 2010,669165933,6 / 27 / 2010,9925,255.28,159.42,2533654.00,1582243.50,951410.50
然后我已经测试了一行脚本:
echo `cat oneline.csv | awk -F, '{ print $1"," $2"," $3"," $4"," $5","}'` `date` `cat oneline.csv |awk -F, '{print $7"," $8"," $9"," $10"," $11"," $12"," $13"," $14"\n"}'
然后我在source.sh中有整个100行文件的代码:
#I want to change 6th value for every line of source.csv to current date and keep the rest and export it to output.csv
while read
do
part1=$(`cat source.csv | awk -F, '{ print $1"," $2"," $3"," $4"," $5","}'`)
datum=$(`date`)
part2=$(`cat source.csv |awk -F, '{print $7"," $8"," $9"," $10"," $11"," $12"," $13"," $14"\n"}'`)
echo `$part1 $datum $part2`
done
,我希望运行./source.sh> output.csv
这样的命令我想要完整的100行文件的结果是: Food,Offline,H, 2019年1月17日星期四06:34:03 ,669165933,6 / 27 / 2010,9925,255.28,159.42,2533654.00,1582243.50,951410.50
您能指导我如何更改代码以获得结果吗?
答案 0 :(得分:3)
将所有内容重构为一个Awk脚本;也可以避免使用echo in backticks。
awk -v datum="$(date)" -F , 'BEGIN { OFS=FS }
{ $6 = datum } 1' source.csv >output.csv
简而言之,我们对逗号(-F ,
)进行分割,并将第六个字段的值替换为我们用-v
传入的变量的值。 OFS=FS
将输出字段分隔符设置为输入字段分隔符(逗号)。那么1
的意思是“无条件打印”。
一般来说,you should probably avoid while read
。
切地,您的报价看起来古怪;您不希望在$part1
周围加反引号,除非它是您要运行Shell的命令(这本身可能是一个坏主意)。而且,反引号长期以来一直被弃用,而倾向于使用$(command)
语法,该语法更易读并且提供一些语法优势。