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.
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
Looks like you need the first and the third fields from the input:
$ echo "79.472850 97 SILENCE" | awk '{print $1, $3}'
79.472850 SILENCE
No need to call external programs like sed
or cut
, or other languages like awk
, bash can do it 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 (start of text).
${var:14}
copies from character position 14 to the end of text.
Alternatively, if it is space-delimited fields you need:
read one two three <<< "$var"
echo "$one $three"
79.472850 SILENCE
Again, that uses pure bash.
Here is an awk solution that works even if you have spaces in your third column :
awk '{$2=""; print}' file
Where $2=""
empties the second column and
print
outputs all columns.
if you want to extract exactly like what 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 input, you could use awk: awk '$2="";7'
kent$ echo "79.472850 97 SILENCE"|awk '$2="";7'
79.472850 SILENCE
来源:https://stackoverflow.com/questions/18186481/remove-the-middle-n-characters-from-lines-in-bash