PuneetGupta PuneetGupta - 7 months ago 24
Bash Question

Remove characters from specific length

How can I remove the set of characters from a specified length in a file using shell script.
Example:

Filename :

abc.txt


helloshell


Now how can I remove characters starting from 8 to 10 (the
ell
at the end)?

I have tried
sed -r
command on Linux servers but it's not working on AIX servers.

Linux command:

sed -r 's/.(.{3}).*/\1/' filename.txt

Answer
$ sed -r 's/^(.{7}).{0,3}(.*)$/\1\2/g'
helloshell
hellosh
1234567890
1234567
$

{0,3} ensures 3 or less chars from 8th position (0,3 implies remove only if present and hence also removes 1/2/3 chars from 8th position) i.e match and remove minimum 0 chars(for no chars) and maximum 3 chars

If you want exactly only 3 chars to removed from 8th position use {3} but it wont remove chars from 8th position if there are less than 3 chars, eg:

$ sed -r 's/^(.{7}).{3}(.*)$/\1\2/g'
123456789
123456789
$