求助:Shell脚本提取Hive日志中指定用户值失败
Hey there! Let's get that username extracted from your HiveServer2 log properly.
First, let's break down why your original awk command didn't work:
awk 'BEGIN{ print "User" } /\<user\>/{ u=$10 } //{ print u }' OFS=',' hive-server2.log
You used the regex /\<user\>/ (which translates to looking for <user> with escaped brackets), but your log line has the plain text user a8197zz—no angle brackets at all. That means the regex never matches any lines, so the u variable never gets set, hence the empty output.
Here are a few solid solutions for you:
1. Simple Field Extraction (works for your current log format)
Since you already know the username is the 10th space-separated field in the filtered lines, you can combine grep and awk like this:
cat hive-server2.log | grep "user" | awk '{print $10}'
Or skip the grep entirely and let awk handle the filtering:
awk '/user / {print $10}' hive-server2.log
This will directly output a8197zz from your sample log line.
2. Robust Regex Capture (handles potential log format changes)
If you want a solution that's less dependent on field positions (in case the log structure shifts slightly), use awk's match() function with a capture group to target the username specifically:
awk 'match($0, /user ([a-zA-Z0-9]+) \(auth:PROXY\)/, match_arr) {print match_arr[1]}' hive-server2.log
This regex looks for the pattern user [username] (auth:PROXY) and extracts the username part, so even if other fields move around, it will still find the right value.
Bonus Tip
If you want to add a header like your original attempt, you can adjust the command to:
awk 'BEGIN{print "User"} /user / {print $10}' hive-server2.log
内容的提问来源于stack exchange,提问作者Arun Kumar

