我有一个包含如下数据的文本文件:
This is just text
-------------------------------
Username: SOMETHI C: [Text]
Account: DFAG Finish time: 1-JAN-2011 00:31:58.91
Process ID: 2028aaB Start time: 31-DEC-2010 20:27:15.30
This is just text
-------------------------------
Username: SOMEGG C: [Text]
Account: DFAG Finish time: 1-JAN-2011 00:31:58.91
Process ID: 20dd33DB Start time: 12-DEC-2010 20:27:15.30
This is just text
-------------------------------
Username: SOMEYY C: [Text]
Account: DFAG Finish time: 1-JAN-2011 00:31:58.91
Process ID: 202223DB Start time: 15-DEC-2010 20:27:15.30
有没有办法从这种数据中提取用户名,完成时间,开始时间?我正在寻找一些使用R或Powershell的起点。
最佳答案
R可能不是处理文本文件的最佳工具,但是您可以按照以下步骤进行操作:通过将文件读取为固定宽度的文件来识别两列,通过在冒号上拆分字符串将字段与其值分开,并添加一个“id”列,然后将所有内容放回原处。
# Read the file
d <- read.fwf("A.txt", c(37,100), stringsAsFactors=FALSE)
# Separate fields and values
d <- d[grep(":", d$V1),]
d <- cbind(
do.call( rbind, strsplit(d$V1, ":\\s+") ),
do.call( rbind, strsplit(d$V2, ":\\s+") )
)
# Add an id column
d <- cbind( d, cumsum( d[,1] == "Username" ) )
# Stack the left and right parts
d <- rbind( d[,c(5,1,2)], d[,c(5,3,4)] )
colnames(d) <- c("id", "field", "value")
d <- as.data.frame(d)
d$value <- gsub("\\s+$", "", d$value)
# Convert to a wide data.frame
library(reshape2)
d <- dcast( d, id ~ field )
关于r - 如何使用R或PowerShell从文本文件中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8987536/