I have a file and I want to write a command that deletes the block based on the word.
If I want to delete [email protected]
the deletion start from the word user
to }
character.
file:
user "sara" {
first_name = "Sara"
login = "[email protected]"
}
user "john_smith" {
first_name = "John"
login = "[email protected]"
last_name = "Smith"
}
I am a beginner at sed and grep commands
I would appreciate it if someone help!
CodePudding user response:
It might be a little difficult to get the results you're looking for using just grep and sed. If you're able to use perl, though, this should work:
# cat test.txt
user "sara" {
first_name = "Sara"
login = "[email protected]"
}
user "john_smith" {
first_name = "John"
login = "[email protected]"
last_name = "Smith"
}
user "sara" {
first_name = "Sara"
login = "[email protected]"
}
user "john_doe" {
first_name = "John"
login = "[email protected]"
last_name = "Doe"
}
# perl -pe 'BEGIN {$/ = "}"} undef $_ if /sara\@example.com/' test.txt
user "john_smith" {
first_name = "John"
login = "[email protected]"
last_name = "Smith"
}
user "john_doe" {
first_name = "John"
login = "[email protected]"
last_name = "Doe"
}
Commented code below:
# Run with the -p flag to, by default, print every line in the file being read
BEGIN {
# Set the INPUT_RECORD_SEPARATOR variable to a closing curly brace
# This causes Perl to treat each block as a separate "line"
$/ = "}";
}
# If the current block contains "[email protected]", don't print anything.
# Note that the ampersand (@) character has to be escaped with a backslash as seen below
undef $_ if /sara\@example.com/;
CodePudding user response:
This might work for you (GNU sed):
sed '/user/{:a;/}/!{N;ba};/sara@example\.com/d}' file
Gather up lines starting with a line that contains user
and ending when another (or the same) line contains }
.
If the collection contains the string [email protected]
, then delete those lines.