简体   繁体   English

从Bash中的行中删除中间的n个字符

[英]Remove the middle n characters from lines in Bash

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: 由于每一行都有不受欢迎的部分从字符10开始到字符14结束,我试图以这种方式使用sed:

sed "s/\\(.\\{9\\}\\).\\{6\\}//" but I just end up with everything after character 14. The numbers following the tab space change in every file. sed "s/\\(.\\{9\\}\\).\\{6\\}//"但我最终得到了字符14之后的所有内容。每个文件中标签空间后面的数字都会发生变化。 What can I do to make sed just cut out the tab and two digits? 我该怎么做才能使sed切掉标签和两位数字?

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. tr -s " "删除重复的空格。
  • cut -d" " -f1,3 prints 1st and 3rd field based on splitting by spaces. cut -d" " -f1,3根据空格分割打印第1和第3个字段。

With sed : 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: 无需调用sedcut等外部程序,或其他语言如awkbash可以为您完成:

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:0:9}从位置0(文本开头)开始复制9个字符。

${var:14} copies from character position 14 to the end of text. ${var:14}从字符位置14复制到文本末尾。

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. 再次,这使用纯粹的bash。

Here is an awk solution that works even if you have spaces in your third column : 这是一个awk解决方案,即使您的第三列中有空格也可以使用:

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

Where $2="" empties the second column and print outputs all columns. 其中$2=""清空第二列并print输出所有列。

if you want to extract exactly like what you described with sed: 如果你想完全像你用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' 如果你想从你的空格分隔输入中提取第1和第3 /最后一列,你可以使用awk: awk '$2="";7'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM