Reputation: 13
I'm quite new to bash and I'd like to know how to find a string in a file and delete two lines starting from this found string.
My file is formatted like this :
username
pass
username2
pass2
username3
pass3
And I would like to delete one specific user for example :
./deleteftpuser username2
And have the file like
username
pass
username3
pass3
I think I should use sed command but I don't know how should I use it.
Thanks a lot for helping !
Upvotes: 1
Views: 124
Reputation: 23667
With GNU sed
$ cat ip.txt
username
pass
username2
pass2
username3
pass3
$ sed '/username2/,+1d' ip.txt
username
pass
username3
pass3
This searches for line matching username2
and then deletes that line plus one line after. Change it to +2
to delete two lines after and so on
Generic solution with perl
$ perl -ne 'if(/username2/){ $l = <> foreach(1..1) } else{ print }' ip.txt
username
pass
username3
pass3
$ perl -ne 'if(/username2/){ $l = <> foreach(1..2) } else{ print }' ip.txt
username
pass
pass3
$ # can also use: perl -pe 'if(/username2/){ undef $_; <> foreach(1..2) }' ip.txt
Upvotes: 0
Reputation: 42017
With GNU sed
:
sed '/username2/ {N; d}' file.txt
With awk
:
awk '/username2/ {np=1; next}; !np {print} np {np=0}' file.txt
Example:
% cat file.txt
username
pass
username2
pass2
username3
pass3
% sed '/username2/ {N; d}' file.txt
username
pass
username3
pass3
% awk '/username2/ {np=1; next}; !np {print} np {np=0}' file.txt
username
pass
username3
pass3
Upvotes: 1
Reputation: 37404
Yet another awk solution. p
is only set if $0
or p
is username2
and next
occurs in that case:
$ awk '($0=="username2" || p=="username2") && p=$0 {next} 1' file
username
pass
username3
pass3
Upvotes: 0
Reputation: 1770
Grep solution-
$cat file
username
pass
username2
pass2
username3
pass3
grep -A 1 "username2" file > temp
grep -vf temp file
Store the search string and one line after it in file temp
.
Then get everything else from the file.
Output-
username
pass
username3
pass3
Upvotes: 0
Reputation: 18371
sed -e '/username2/ { N; d; }' infile
username
pass
username3
pass3
Upvotes: 0