Search code examples
stringbashsplitdd

How to split a delimited string to compose a dd command in bash?


I would like to read a config file that should look similar to what is shown below:

source/path:blocksize,offset,seek,count
source/path2:blocksize,offset,seek
source/path3:blocksize,offset

Where source/path,source/path2 and source/path3 are paths to some binary file and offset, seek, count and blocksize are respective values for dd command.
Note that the variables may vary, like some binary file may not have seek or both seek and count values for dd command.

How should I split the above lines to compose dd command like this
dd if=${source/path} bs=${blocksize} seek=${seek} count=${count}
dd if=${source/path} bs=${blocksize} seek=${seek}
dd if=${source/path} bs=${blocksize}?

It is ok if modification is required in the above format to make it easy for parsing cause I ran out of all possibilities that my naive mind can think of.


Solution

  • Hope this helps:

    $ cat <<EOF | while read line; do arr=($(sed 's/[,:]/ /g' <<< $line)); echo "source:${arr[0]}  block:${arr[1]} offset:${arr[2]} seek:${arr[3]} count:${arr[4]}"; done
    source/path:blocksize,offset,seek,count
    source/path2:blocksize,offset,seek
    source/path3:blocksize,offset
    EOF
    source:source/path  block:blocksize offset:offset seek:seek count:count
    source:source/path2  block:blocksize offset:offset seek:seek count:
    source:source/path3  block:blocksize offset:offset seek: count:
    

    General Idea:

    #!/usr/bin/env bash
    
    your_command | while read line; do 
            arr=($(sed 's/[,:]/ /g' <<< $line)); 
            echo "source:${arr[0]}  block:${arr[1]} offset:${arr[2]} seek:${arr[3]} count:${arr[4]}"
            
            # Do whatever processing & validation you want here
            # access from array : ${arr[0]}....${arr[n]}
            #
    
     done
    

    If you're having file then:

    #!/usr/bin/env bash
    
    while read line; do
           arr=($(sed 's/[,:]/ /g' <<< $line)); 
           echo "source:${arr[0]}  block:${arr[1]} offset:${arr[2]} seek:${arr[3]} count:${arr[4]}"
            
            # Do whatever processing & validation you want here
            # access from array : ${arr[0]}....${arr[n]}
            #
    
    done < "path/to/your-file"