我有一个类似的文件:
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),添加一个逗号(,)然后将该行的编号放在newfile.txt中(132,0,43.0,0.0,43.0,210.0)之前 新文件应如下所示:(原始文件在行之间没有空格)
20110113, 132.0, 43.0, 0.0, 0.0, 43.0,210.0
我尝试了grep和sed没有运气。谢谢你的帮助
答案 0 :(得分:1)
以下是我如何解释您的问题:
你正试图'grep'并加入两行的部分。这两行总是第二行和第二行。
您还尝试将输出重定向到另一个文件。您可以使用shell redirection,例如: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.
答案 1 :(得分: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