Remove exactly one line in a file
I have a file that contains the following lines:
SUKsoft:
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
How can I remove the line "SUKsoft:"?
This line could be in any place of the file (beginning as it is now, or in the middle).
Is there a command to do this?
Solution 1:
To remove the line use
sed -i '/SUKsoft:\s*$/d' your_file
Example
% cat foo
SUKsoft:
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
% sed -i '/SUKsoft:\s*$/d' foo
% cat foo
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
Solution 2:
Here are the steps to remove the desired line:
$ sed 's/SUKsoft: *$//' file.txt
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
I am assuming file.txt
contains the lines.
Or,
$ sed 's/SUKsoft: *$//; /^$/d' file.txt
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
it does not leave any blank line.
To edit in the file you can use,
sed -i 's/SUKsoft: *$//' file.txt
or
sed -i 's/SUKsoft: *$//; /^$/d' file.txt
as per your need.
See A.B's answer where it is done in more compact manner. Thanks to Wildcard.
Solution 3:
grep
searches for lines that satisfy a pattern. grep -v
discards lines that satisfy a pattern.
grep -v '^SUKsoft: *$'
The pattern is: lines that start (^
) with SUKsoft:
, possibly followed by spaces but nothing else until the end of the line ($
).
Solution 4:
Judging from your post't raw source there's no space or sequence of spaces after "SUKsoft:", however just to be on the safe side this command will take care of those if present.
Using Perl:
perl -ne '!/^SUKsoft: *$/&&print' input
-
!/^SUKsoft:$/&&print
: if the current line doesn't match the pattern^SUKsoft: *$
, which matches a line starting withSUKsoft:
string followed by zero or more spaces, prints the line;
% cat input
SUKsoft:
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW
% perl -ne 'print unless /^SUKsoft: *$/' input
SUKsoft: App-Conduct_Risk_Comment
SUKsoft: App-Conduct_Risk_R
SUKsoft: App-Conduct_Risk_RW