I have a file with "n" number of lines. I need to get rid of a specific line having a specific string from the file. I tried some possibilities but not successful.
For ex: in a file named "test"
hope should be removed along with the line.
@RudiC My requirement is both as you could see from the first line "hope" lies between :*hope*: the other line doesn't have any : so, it should remove the entire content.
@MadeInGermany
I have used the regex for replacing words with others, not in an expected way. so, I am not aware of the pattern to be used.
It is usually best and most efficient for all parties to carefully phrase the request in the first place, cogitating all the possible ramifications e.g. difference in structures and positions in files. Better than letting drip in information droplet by droplet after a solution was found for the first but non-fitting sample.
The easiest way would be to force the long lines into several independent ones:
tr ' ' '\n' < file | sed ...
The logics lie in the regex: find a string of zero or more colons (parenthesized for later "back reference") then any number of non-colons, the "hope" string, non-colons again, and finally zero or more colons. Replace by the first colon if exists else the empty string (i.e. remove)
For this case, the proposed condition is failing,
Sorry for not representing this earlier, because, I didn't predict that my output will yield this patterns
The following deletes a :something/hope/something that follows a PASS= at the beginning of the line.
sed -n 's#\(^PASS=[^ ]*\):[^: ]*/hope/[^: ]*#\1#p' file
The -n option suppresses the default print, the p modifier prints if a substitution was made.
The part that is captured between \( \) is restored by the \1 .