在unix bash中为每行csv文件添加一天

时间:2015-03-11 06:38:07

标签: bash unix csv text

我试图教自己unix bash来操纵大文本文件(在这种情况下为.CSV)。我想根据该行中的日期将星期几添加到文件的每一行。我对如何完成单个零件有一些了解,但不能将这些零件放在一起。任何帮助将非常感激。干杯。

要查找每个日期(我也需要在列之间插入逗号):

sed -i.bak "s/(0-9)(0-9)\/(0-9)(0-9)\/(0-9)(0-9)(0-9)(0-9)/\1\2,\3\4,\5\6/" datafile.txt

查找星期几(以20150311为例。我想使用该行中的日期):

date -d 20150311 +%A

我怎么能以某种方式将这些放在一起?我知道我需要在正则表达式中创建一个变量,使用上面的date命令,然后以某种方式将它附加到每行的末尾:

sed -i.bak "s/$/,DAYVARIABLE/" datafile.txt 

假设数据文件的格式如下:

RandomString,AnotherRandomString,01/01/1982,MoreRandomString

再次感谢

3 个答案:

答案 0 :(得分:2)

GNU sed有一个扩展,允许您在替换部分中嵌入外部命令,但为了便于携带和清晰,我将切换到另一个工具。

perl -MPOSIX -i.bak -pe 's|(,(\d{2})/(\d{2})/(\d{4}),.*)|
   "$1," . strftime("%A", 0, 0, 0, $2, $3-1, $4) |e' file.csv

假设您的日期是dd / mm / yyyy;如果你的输入是(古怪的)美国mm / dd / yyyy,则在$2$3之间交换。

这是使用Perl POSIX strftime模块,它接受一个相当复杂的参数列表来指定日期(它是由Perl标准localtime函数返回的7元素列表)。有各种包装器可以实现更方便的日期处理,但它们不包含在标准的Perl库中,因此它们会添加外部依赖项。

答案 1 :(得分:1)

您可以使用简单的command substitution作为

sed "s/$/, $(date -d 20150311 +%A)/" 

<强>测试

$ cat input
qwerty
asdf 
abb asdf
bbb
zxc
abc
qweabcqwe

$ sed "s/$/, $(date -d 20150311 +%A)/" input
qwerty, Wednesday
asdf , Wednesday
abb asdf, Wednesday
bbb, Wednesday
zxc, Wednesday
abc, Wednesday
qweabcqwe, Wednesday

答案 2 :(得分:0)

您可以使用此脚本:

示例输入:

cat file
RandomString,AnotherRandomString,01/01/1982,MoreRandomString
FooBar,AnotherRandomString,01/10/1990,SomeRandomString

<强>代码:

while IFS=, read -ra arr; do
    len=$((${#arr[@]} - 2))
    printf "%s," "${arr[@]}"
    date -d "${arr[$len]}" '+%A'
done < file

<强>输出:

RandomString,AnotherRandomString,01/01/1982,MoreRandomString,Friday
FooBar,AnotherRandomString,01/10/1990,SomeRandomString,Wednesday

<强>解释

IFS=, read -ra arr            # populate an array arr with comma as separator
len=$((${#arr[@]} - 2))       # get length(array) -1 in len to extract date
printf "%s," "${arr[@]}"      # print array arr with comma as field separator
date -d "${arr[$len]}" '+%A'  # print day of the week for date value