I'm trying to parse various info from log files, some of which is placed within square brackets. For example:
Tue, 06 Nov 2007 10:04:11 INFO processor:receive: [someuserid], [somemessage] msgtype=[T]
What's an elegant way to grab 'someuserid' from these lines, using sed, awk, or other unix utility?
cut
use it like this: cut -f2 -d[ | cut -f1 -d]
cut -f2 -d[ | cut -f1 -d]
bart@hal9k:~> YOURTEXT="Tue, 06 Nov 2007 10:04:11 INFO processor:receive: [someuserid], [somemessage] msgtype=[T]"
bart@hal9k:~> SOMEID=`echo $YOURTEXT | cut -f2 -d[ | cut -f1 -d]`
bart@hal9k:~> echo $SOMEID
someuserid
using bash shell
while read -r line
do
case "$line" in
*processor*receive* )
t=${line#*[}
echo ${t%%]*}
;;
esac
done < "file"
sed -n '/INFO/{s/.[^[]*\[//;s/\].*//p}' file
Using AWK:
cat file | awk -F[\]\[] '{print $2}'
I have found that multiple delimiters do not work in some older versions of AWK. If it doesn't, you can use two awks:
cat file | awk -F[ '{print $2}' | awk -F] '{print $1}'
If you want to do something with all the bracketed fields, I'd use Perl:
perl -lne '
my @fields = /\[(.*?)\]/g;
# do something with @fields, like:
print join(":", @fields);
' logfile ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.