我有一个包含以下数据的文本文件:
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。
答案 0 :(得分:8)
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 )
答案 1 :(得分:2)
这些只是我如何解决问题的指导原则。我确信这是一种更奇特的方式。可能包括plyr。 :)
rara <- readLines("test.txt") # you could use readLines(textConnection = "text"))
# find usernames
usn <- rara[grepl("Username:", rara)]
# you can find a fancy way to split or weed out spaces
# I crudely do it like this:
unlist(lapply(strsplit(usn, " "), "[", 2)) # 2 means "extract the second element"
# and accounts
acc <- rara[grepl("Account:", rara)]
unlist(lapply(strsplit(acc, " "), "[", 2))
您可以使用str_trim()
删除单词之前/之后的空格。希望有足够的指示让你前进。
答案 2 :(得分:2)
这是一个Powershell解决方案:
$result = @()
get-content c:\somedir\somefile.txt |
foreach {
if ($_ -match '^Username:\s+(\S+)'){
$rec = ""|select UserName,FinishTime,StartTime
$rec.UserName = $matches[1]
}
elseif ($_ -match '^Account.+Finish\stime:\s+(.+)'){
$rec.FinishTime = $matches[1]
}
elseif ($_ -match '^Process\sID:\s+\S+\s+Start\stime:\s+(.+)'){
$rec.StartTime = $matches[1]
$result += $rec
}
}
$result
答案 3 :(得分:0)
您的文件是否在数据框中?与列名称一样,用户名,进程ID,开始时间......如果是,您可以通过
轻松提取它df$Username (where df is your data frame and if you want to see all your usernames)
df$FinishTime
如果您想了解具有特定名称的用户的所有信息,请使用此
df[df$username == "SOMETHI",]
如果您想了解完成时间的用户..
希望这可以作为一个起点。如果不清楚,请告诉我。