bash script search string and delete the line above

we search a string "test" in file.txt file, then delete its line above.
 hans@testvm:~ $ cat ./del_line_above.sh
#!/bin/bash
line_number="$(grep -n 'test' file.txt| cut -d: -f1)"
line_number_above="$((line_number - 1))"
sed "${line_number_above}d" file.txt

 hans@testvm:~ $ cat file.txt
aadsfasfda
line 1
line 2
line 3
line 4
test
java
hans@testvm:~ $ ./del_line_above.sh
aadsfasfda
line 1
line 2
line 3
test
java

Leave a Reply

Your email address will not be published. Required fields are marked *