Bash - truncate even lines in txt file

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

Input:

1
AABBBBBCCC
2
GKDDABC

      

let X = 2 and Y = 3:

1
BBBBB
2
DD

      

+3


source to share


4 answers


Usage 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 parameters -v

    define our two variables, x

    and y

    .

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

    NR is the row count. When 0 == NR%2

    , we are on an even line and delete characters x

    from the beginning and y

    from the end. B awk

    , $0

    - the whole line. We replace with a substring that starts at position x+1

    and has length length($0)-y-x

    .

  • 1

    This is a critical shorthand for printing a line.

+3


source


Gnu sed has a step address operator ~

. 2~2

means "start on line 2, match every other line".



x=2 
y=3 
sed "2~2{s/^.\{$x\}//;s/.\{$y\}$//}" input

      

+3


source


perl -pE '$_=substr($_,'$x',-'$y')."\n" unless $. %2'

      

+2


source


This might work for you (GNU sed):

sed -r 'n;s/^.{2}(.*).{3}$/\1/' file

      

or if you want to parameterize:

x=2 y=3
sed -r "n;s/^.{$x}(.*).{$y}$/\1/" file

      

Where n

prints lines of odd lines on even lines for a substitution command.

0


source







All Articles