Remove middle characters from strings in Bash

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

79.472850 97 SILENCE 

and I need to end up with:

 79.472850 SILENCE 

Since each line has an undesirable part starting with character 10 and ending with character 14, I tried to use sed this way:

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

Thanks for your help.

+4
source share
5 answers

According to your input and expected output, this could be a way:

 $ echo "79.472850 97 SILENCE" | tr -s " " | cut -d" " -f1,3 79.472850 SILENCE 
  • tr -s " " removes duplicate spaces.
  • cut -d" " -f1,3 prints 1st and 3rd fields based on space breaks.

With sed :

 $ sed 's#\([^ ]*\)[ ]*\([^ ]*\)[ ]*\([^ ]*\)#\1 \3#g' <<< "79.472850 97 SILENCE" 79.472850 SILENCE 
+8
source

It looks like you need the first and third fields from the input:

 $ echo "79.472850 97 SILENCE" | awk '{print $1, $3}' 79.472850 SILENCE 
+4
source

No need to call external programs such as sed or cut , or other languages ​​such as awk , bash , can do this for you:

 var="79.472850 97 SILENCE" echo ${var:0:9}${var:14} 79.472850 SILENCE 

${var:0:9} copies 9 characters starting at position 0 (beginning of text).

${var:14} copies from character position 14 to the end of the text.

Alternatively, if you need spatially separated fields:

 read one two three <<< "$var" echo "$one $three" 79.472850 SILENCE 

Again, this uses pure bash.

+3
source

Here is an awk solution that works even if you have spaces in the third column:

 awk '{$2=""; print}' file 

Where $2="" empties the second column and print prints all the columns.

+2
source

if you want to extract exactly the same as you described with sed:

 kent$ echo "79.472850 97 SILENCE"|sed -r 's/(^.{9})(.{4})(.*)/\1 \3/' 79.472850 SILENCE 

if you want to extract the 1st and 3rd / last columns from your space-separated section, you can use awk: awk '$2="";7'

 kent$ echo "79.472850 97 SILENCE"|awk '$2="";7' 79.472850 SILENCE 
+1
source

Source: https://habr.com/ru/post/1496566/


All Articles