Ubuntu – How to we remove text from start to some particular selected word using sed command in linux

bashcommand linesed

I have a simple query related to selection and replacing text in linux. I am using sed command. I have the following text:

hello world, I am just simple text for display.

Now I want to print to "hello world" only I can do it using following command in linux.

echo "hello world, I am just simple text for display." | sed 's/, I am.*//g'

Now I want totally inverse of this function, how can I remove "hello world" by using a simple command just like sed.

Output required:

, I am just simple text for display.

I would prefer if linux commands (sed etc) are used.

Best Answer

To reverse the effect of your command AND keeping the same part of the string to be matched (assuming that this is the only fix part of the string and you want to get rid of any other part that may vary), you can do :

echo "hello world, I am just simple text for display." | sed 's/^.*\(, I am.*\)/\1/g'

Result :

, I am just simple text for display

What the regular expression is doing :

  • ^.* : matching any character at the beginning of the string until the next expression
  • \( & \) : to catch the part of the string which is matched by the expression in between (must be escaped by \ or they will match the parenthesis character).
  • , I am.* : the match you give us,
  • \1 : will be replaced by the result of the match of the first sub-expression between parenthesis

This way, you have the exact reverse effect of the command in your question, using the same part of the string to do the match.

Related Question