Reputation: 47
I have a bash script that is parsing files containing information about processes running on a server. Everything works except the output.
Target output
tomcat7 Running Monitored 3025 18d 2h 16m 3.6% 0.0%
What it actually is outputing
0.0%2h 16m ing
Script portion doing the parsing and output
for SERVER in $SERVERS ; do
SYSTEM=$(sed -n '/System/{p; n;p; n;p; n;p; n;p; n;p}' $H_DIR/$SERVER.txt)
sed -n '/Process/{p; n;p; n;p; n;p; n; n;p; n;n;n; n;p; n; n;p}' $H_DIR/$SERVER.txt > $H_DIR/procs.txt
split --lines=7 $H_DIR/procs.txt $H_DIR/procs.txt.
for PROC in $H_DIR/procs.txt.?? ; do
PROCESS=$(cat $PROC | head -1 | tail -1 | cut -d "'" -f2)
STATUS=$(cat $PROC | head -2 | tail -1 | awk '{ print $NF }')
MONITOR=$(cat $PROC | head -3 | tail -1 | awk '{ print $NF }')
PID=$(cat $PROC | head -4 | tail -1 | awk '{ print $NF }')
UPTIME=$(cat $PROC | head -5 | tail -1 | awk '{ print substr($0, index($0, $2)) }')
PCPU=$(cat $PROC | head -6 | tail -1 | awk '{ print $NF }')
PMEM=$(cat $PROC | head -7 | tail -1 | awk '{ print $NF }')
echo $PROCESS $STATUS $MONITOR $PID $UPTIME $PCPU $PMEM
done
rm -f $H_DIR/procs.*
rm -f $H_DIR/$SERVER.txt
done
raw file being parse
Process 'tomcat7'
status Running
monitoring status Monitored
pid 3025
uptime 18d 2h 30m
memory percent 3.6%
cpu percent 0.0%
Upvotes: 0
Views: 172
Reputation: 11582
On a hunch - your input files have the DOS carriage return line feed combination.
I added that to your file and got the same results you did.
See this question for how to remove the carriage return:
Remove carriage return in Unix
Using the suggested tr -d '\r'
method for removing carriage return (and might as well remove single quotes at the same time) you could do something like this:
echo $(tr -d "\r\'" < $PROC | awk 'NR==5{print substr($0,index($0,$2))}{print $NF}')
or if you need each variable assigned then something like this
VARS=$(tr -d "\r\'" < $PROC | awk 'NR==5{print substr($0,index($0,$2))}{print $NF}')
read PROCESS STATUS MONITOR PID UPTIME PCPU PMEM <<<$VARS
echo $PROCESS $STATUS $MONITOR $PID $UPTIME $PCPU $PMEM
Either way, output is
tomcat7 Running Monitored 3025 18d 2h 30m 30m 3.6% 0.0%
Upvotes: 2