Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a simple query related to selection and replacing text in linux. For explaning question I am using sed command. I have 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 simple command just like sed.
Output required. , I am just simple text for display. It will very fruitful if linux commands (sed etc) are used. Thanks

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks man! That's exactly what I was looking for. Above mentioned methods also worked, but I think this one is cool. –  Muhammad Abdullah Jul 10 at 8:29

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

Explanation: in sed (and elsewhere, like in vim), use carat (^) to indicate start of line. The substitution removes just that text.

share|improve this answer

You could use the sed option s. The command will be,

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

gives

I am just simple text for display.

Explanation

  • .* matches any number of any characters
  • ,<space> matches , and space
  • So the combination .*,<space> matches everything before , and space including both, and replaces them with nothing.
share|improve this answer
    
This was also a perfect logic for fetching required text from strings, thanks mate! –  Muhammad Abdullah Jul 10 at 8:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.