Search code examples
linuxsedcut

Linux cut command - capture string between multiple positions


I have a text file containing very long lines. I want to get only parts of the file by specifying several positions.

I tried cut but it seems to give just the opposite reverse of what I need; it captures only what I don't want.

My cut code:

/bin/cat file.txt | /usr/bin/cut -f50-62,3414-5706427

My expected result is to have the entire file except for characters 50-62 and characters 3414-5706427.

I've also thought of sed but found no way to make sed get me out just the data I need. Is there any Linux command to reverse the result?


Solution

  • edit: there is an option to cut which looks like it does what you want:

    echo "abcdefghikjl" | cut -c2-4
    bcd
    echo "abcdefghikjl" | cut -c2-4 --complement
    aefghikjl
    

    Otherwise, you could use native bash string manipulation:

    #!/bin/bash
    
    function revcut() { 
        echo "${1/${1:$2:$3-$2}/}"; 
    }
    

    usage:

    revcut "some string" start end
    

    from a file:

    revcut "$(cat filename)" start end