Search code examples
bashsedposix

String Alteration Using Sed


Once i execute | xxd -bi, I get the output as

00000000: 01101000 01100101 01101100 01101100 01101111 00001010 hello.

Now I am trying to remove initial 0000000, which I did using sed and I am trying to remove "hello" (variable text) which is stored in $covertthis using sed but I can't achieve so, as shown below in the example please suggest me the changes.

I have tried using cut aswell but can't alter both 0000000 and last variable word.

echo "What you want to input numbers or string?"
read input

if [[ "$input" == "number" ]] || [[ "$input" == "Number" ]] || [[ "$input" == "NUMBER" ]] ;then
        echo "Number selected 1"
elif [[ "$input" == "String" ]] | [[ "$input" == "STRING" ]] || [[ "$input" == "string" ]] ;then
        echo "String selected"
        echo "Please give me the string to be XOR'ed"
        read convertthis
        echo  $convertthis | xxd -bi > bin-store
        $(sed -i -e 's/00000000://g' bin-store)
        $(sed -i -e 's/($convertthis).//g' bin-store)
else
        echo "Please re-run the script, input is wrong"
fi

Solution

  • You need only one sed for that. Separate commands using ;

    # read convert_this
    echo "00000000: 01101000 01100101 01101100 01101100 01101111 00001010  hello." | 
    sed -E "s/^[^[:blank:]]*[[:blank:]]+//;s/[[:blank:]]+$convert_this\.$//" 
    

    should do it.

    Output

    01101000 01100101 01101100 01101100 01101111 00001010
    

    Explanation

    • The -E option with sed enables the use of Extended regular expressions.
    • s/^[^[:blank:]]*[[:blank:]]+//; The ^ in the beginning looks for the start of the line. [] in sed is meant for ranges. If the range begins with a ^ that means you're negating a range. The * looks is meant for zero or more and + is meant for one or more. The [:blank:] is a character class matching any blank characters like whitespaces tabs and so. In short we are looking for any non-blank characters in the beginning followed by one or more spaces. Then we substitute it with nothing effectively deleting it.
    • The second substitute replaces the string stored in $convert_this and any full-stop that follows with nothing.

    All good :-)


    Sidenote: You need to use double quotes to wrap the sed commands so that your bash variables are expanded.