1

我有一个像这样的文件:

something1

something2 201101130000

thing

thing1

thing2

AAA, -2, 4, 0, 54;

thing3

thing4

AAA, 43, 43, 0, 5, 0, 0,;

thing5

AAA, 132.0, 43.0,  0.0,  0.0, 43.0,210.0,'

thing5

如何从第二行复制日期 (201101130000),添加逗号 (,),然后将最后一行的数字 (132,0, 43.0, 0.0, 43.0, 210.0) 放入 newfile.txt 新文件应该看起来像:(原始文件在行之间没有空格,因为它在这里)

20110113, 132.0, 43.0,  0.0,  0.0, 43.0,210.0

我尝试了 grep 和 sed,但没有成功。谢谢你的帮助

4

2 回答 2

1

以下是我对您的问题的解释:

  • 您正在尝试“grep”并连接两行的部分内容。这两行始终是倒数第二行和倒数第二行。

  • 您还试图将输出重定向到另一个文件。您可以为此使用shell 重定向,例如:awk ... file > outputfile.



这是一种使用方法sed

sed '2h; $!N; $!D; ${ G; s/[^,]*\([^\n]*\).* \([0-9]\{8\}\).*/\2\1/; s/..$// }' file

既然您已将其标记为 linux,我猜您已经拥有GNU sed并且不介意打高尔夫球:

sed -r '2h;$!N;$!D;${G;s/[^,]*([^\n]*).*\s([0-9]{8}).*/\2\1/;s/..$//}' file

结果:

20110113, 132.0, 43.0,  0.0,  0.0, 43.0,210.0

解释:

2h         # copy the second line to hold space
$!N        # if not the last line append the next line
$!D        # if not the last line delete up to the first newline in the pattern
$ { ... }  # one the last line, perform two substitutions   


或者,awk可能更容易理解:

awk 'FNR==NR { c++; next } FNR==2 { x = substr($NF,0,8) } FNR==c-1 { sub(/[^,]*/,x); sub(/..$/,""); print }' file file

结果:

20110113, 132.0, 43.0,  0.0,  0.0, 43.0,210.0

解释:

FNR==NR { c++; next }    # read the first file in the arguments list, to get a 
                         # count of the number of lines in the file
FNR==2 { ... }           # when reading the second line of the second file in the
                         # arguments list, take a substring of the last field
FNR==c-1 { ... }         # one the second last line of the second file in the
                         # arguments list, perform two substitutions and print
                         # the line.
于 2013-02-06T19:14:40.057 回答
0

AWK做的伎俩:

awk '/something[0-9][ ]*[0-9]+/{d = $2;} /AAA/{v = $0;} END{gsub("AAA",d,v); print v;}' file.txt

输出是:

201101130000, 132.0, 43.0, 0.0, 0.0, 43.0,210.0
于 2013-02-06T18:51:25.633 回答