首页 > 解决方案 > Deleting the word and the word/character next to it in a string inside file

问题描述

I am looking to solve a particular problem in Bash scripting

Consider file.txt

AAAA BBBB  CCCC D  EEEE F  

I am looking to delete CCCC and D and restore the space it occupies so that there is not extra space as such

I have tried using sed but to no avail. Tried using the s option but it is working only for the string where I can replace it with ''

The expected result is

AAAA BBBB  EEEE F

标签: bashshell

解决方案


If I'm correctly interpreting that "extra space" means more than one space, then I'm confused as to why the expected result has two spaces between "BBBB" and "EEEE". Assuming you really meant one space, the following should work:

$ echo "AAAA BBBB  CCCC D  EEEE F  " | sed 's/CCCC D//g' | tr -s ' '
AAAA BBBB EEEE F

推荐阅读