Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the middle n characters from lines in Bash

Tags:

bash

unix

sed

cut

I am trying to cut out the middle of each line in a file. All the lines are like this:

79.472850   97 SILENCE 

and I need to end up with:

79.472850 SILENCE

As each line has the undesired portion starting at character ten and ending at character 14, I was trying to use sed in this way:

sed "s/\(.\{9\}\).\{6\}//" but I just end up with everything after character 14. The numbers following the tab space change in every file. What can I do to make sed just cut out the tab and two digits?

Thanks for your help.

like image 379
Felixia Avatar asked Nov 30 '22 20:11

Felixia


1 Answers

As per your input and expected output, this can be a way:

$ echo "79.472850   97 SILENCE" | tr -s " " | cut -d" " -f1,3
79.472850 SILENCE
  • tr -s " " deletes repeated spaces.
  • cut -d" " -f1,3 prints 1st and 3rd field based on splitting by spaces.

With sed:

$ sed 's#\([^ ]*\)[ ]*\([^ ]*\)[ ]*\([^ ]*\)#\1 \3#g' <<< "79.472850   97 SILENCE"
79.472850 SILENCE
like image 70
fedorqui 'SO stop harming' Avatar answered Dec 04 '22 04:12

fedorqui 'SO stop harming'