Bash script that process input from pipeline or file redirection
November 15th, 2008 mysurface Posted in Bash, pipeline | Hits: 107175 |
I remember I wrote a post regarding how to makes python processing string from the pipeline stream. This time, I find the needs to do it in bash script.
I created a hex string splitter script for my friend who needs to decode the raw data that will be written in hex string such as “5F443D95FEA3D4787AEDC4″. Every time, he split them byte by byte manually into this form (“5F 44 3D 95 FE A3 D4 78 7A ED C4″) for better reading. He was complain that the manual process was always bothering him. I told him that can be done by writting a simple bash script.
My hexsplit.sh will do this:
./hexsplit.sh "5F443D95FEA3D4787AEDC4"
But what if he grep this hex string from other file? Or what if the hex string are stored in a file? I want my bash script to be able to process hex string from pipeline stream as well as file redirection too, like this:
grep "hex" dummy.log | cut -d"]" -f2 | ./hexsplit.sh
or like this:
./hexsplit.sh < dummy.log
How to write this hexsplit.sh?
hexsplit.sh
#!/bin/bash
if [ -e $1 ] ;then read str; else str=$1;fi
len=`expr length $str`
for (( a=0; a<=$len; a=a+2 )); do echo -n ${str:a:2}" "; done
echo ""
The important line is the if statement. If there are no argument specified ( -e $1), I read from the stream, else i take it from $1 ( param 1). It is so simple isn’t it?
Have fun!
Live Chat!







November 15th, 2008 at 11:43 am
a<=$len inside the C-style for loop needs to be a<=len or a<=”$len”
November 15th, 2008 at 4:11 pm
Aia: just a<=$len is working for me.
March 2nd, 2009 at 6:08 am
is there a way to become a content writer for the site?