以下是我对您的问题的解释:
这是一种使用方法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.