How do I extract information from a string
I am trying to pull a dynamic out of a load I am running using bash. I got to the point where I get the string I want, now I want to get some information out of it that can change. The returned string looks like this:
Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0
Each of the numbers can and will vary in length, but the overall structure will remain the same. What I want to do is get these numbers and load them into some bash variables, namely:
RECORDS=??
DELETED=??
SKIPPED=??
WARNING=??
In a regex, I would do it like this:
Records: (\d*?) Deleted: (\d*?) Skipped (\d*?) Warnings (\d*?)
and use 4 groups in my variables.
+2
a source to share
5 answers
You can use a shell function here that just creates multiple name / value pairs. It assumes everything is formatted as you said, but easy to change:
parseline() {
while [ $# -ge 2 ] ; do
eval $(echo $1 | tr -d : | tr '[a-z]' '[A-Z]')="$2"
shift 2
done
}
Run it like:
$ parseline Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0
$ echo $RECORDS
2910
$ echo $WARNINGS
0
+1
a source to share
You can try something with "sed" or "cut" depending on the structure of the line:
#!/bin/sh
DYNAMIC="Records: 2910 Deleted: 1 Skipped: 2 Warnings: 3"
RECORDS=`echo "$DYNAMIC" | sed 's/.*Records: \([0-9]*\).*/\1/g'`
DELETED=`echo "$DYNAMIC" | sed 's/.*Deleted: \([0-9]*\).*/\1/g'`
SKIPPED=`echo "$DYNAMIC" | sed 's/.*Skipped: \([0-9]*\).*/\1/g'`
WARNINGS=`echo "$DYNAMIC" | sed 's/.*Warnings: \([0-9]*\).*/\1/g'`
echo "Records $RECORDS"
echo "Deleted $DELETED"
echo "Skipped $SKIPPED"
echo "Warnings $WARNINGS"
echo "$DYNAMIC" | cut -d " " -f2
echo "$DYNAMIC" | cut -d " " -f4
echo "$DYNAMIC" | cut -d " " -f6
echo "$DYNAMIC" | cut -d " " -f8
0
a source to share
#!/bin/bash
s="Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0"
s=${s//: /=}
for i in $(printf ${s// /"\n"})
do
eval $i
done
echo "Records: $Records"
echo "Deleted: $Deleted"
echo "Skipped: $Skipped"
echo "Warnings: $Warnings"
Exit
$ ./shell.sh
Records: 2910
Deleted: 0
Skipped: 0
Warnings: 0
0
a source to share