使用awk重新格式化日期时间

时间:2016-02-20 18:37:52

标签: linux unix awk sed delimiter

我有一个包含这样的行的文件:

2012/04/08 15:00,207
2012/04/08 16:00,180

我想格式化日期,使文件看起来像:

08/04/2012 15:00,207

Awk似乎是正确的工具,但我无法正确捕获组。我尝试过类似以下的内容(Use sed or awk to fix date format):

awk ' BEGIN { FS = OFS = "," } { split($1, date, /\// ) $1 = date[3] "-" date[2] "-" date[1] " " date[4] print $0 } ' $FILE

但它留下了这样的数据:

08 15:00-04-2012,207

Awk的分裂显然将时间解释为日期字符串的年份字段的一部分,而我似乎无法找到将其分开的方法。我在split delimiter字段中尝试了许多不同的东西,例如冒号或转义空格,但都给出了语法错误。看过awk split的文档并没有被它启发。

2 个答案:

答案 0 :(得分:2)

Map<Ships, Double> sortedMap = sortByComparator(shipsarray);
            LinkedHashSet<String> uniqueStrings = new LinkedHashSet<String>();
            double tempprice=0,tempcap=0;
            String tempship = null;

            for (Map.Entry<Ships, Double> entry : sortedMap.entrySet()) {//loop for fill in
                if((double)entry.getValue() == tempprice){
                    if(entry.getKey().getAvailableCapacityForType(user.getContainers().get(i).getClass())>tempcap){
                        System.out.println(uniqueStrings);
                        uniqueStrings.remove(tempship);
                        uniqueStrings.add(entry.getKey().getship().getShipName());
                        uniqueStrings.add(tempship);
                        System.out.println(uniqueStrings);
                    }
                    else{
                        System.out.println(uniqueStrings);
                        uniqueStrings.add(entry.getKey().getship().getShipName());
                    }
                }
                else{
                    uniqueStrings.add(entry.getKey().getship().getShipName());
                    tempprice = (double)entry.getValue();
                    tempship = entry.getKey().getship().getShipName();
                    tempcap = entry.getKey().getAvailableCapacityForType(user.getContainers().get(i).getClass());
                }



            }

仅供参考使用GNU awk或sed作为捕获组:

$ awk '{split($1,date,"/"); print date[3] "/" date[2] "/" date[1], $2}' file
08/04/2012 15:00,207
08/04/2012 16:00,180

答案 1 :(得分:1)

这是一个使用正则表达式fieldsplitting的解决方案,方法是将FS设置为正则表达式,将时间戳分开,然后重新组合它:

awk '
  BEGIN { FS= "[/ ]"; }
  {print $3 "/" $2 "/" $1 " "  $4 ;}
' file
相关问题