Search code examples
bashawksedcuttr

bash- trimming the even lines in txt file


I'd like to remove the first X characters and the last Y characters from all even lines of a file with bash.

Input:

1
AABBBBBCCC
2
GKDDABC

let X=2 and Y=3:

1
BBBBB
2
DD

Solution

  • Using awk:

    $ awk -v x=2 -v y=3 '0==NR%2 {$0=substr($0,x+1,length($0)-y-x)} 1' file
    1
    BBBBB
    2
    DD
    

    How it works:

    • -v x=2 -v y=3

      The -v options define our two variables, x and y.

    • 0==NR%2 {$0=substr($0,x+1,length($0)-y-x)}

      NR is the line counter. When 0 == NR%2, we are on an even line and we remove x characters from the start and y from the end. In awk, $0 is the whole line. We replace with a substring which starts at position x+1 and has length of length($0)-y-x.

    • 1

      This is cryptic shorthand for print the line.