I have a file named file.txt
and it contains several lines containing string "NaN". How can I delete lines containing "Nan" and one line before and after it. I know sed -i '/pattern/d' file.txt
can delete the matched line, but how can I delete neaby lines of the matched line.
Best regards
Asked
Active
Viewed 49 times
0

Winston Pan
- 47
- 6
-
Please do share samples of input and expected output in your question to make your question more clear, thank you. – RavinderSingh13 Aug 26 '21 at 12:04
-
`ed` is probably a more suitable command for tasks like this, though I am not sure how to handle the case where `NaN` is the first or last line in the file. `printf 'g/NaN/-,+d\nwq\n' | ed file.txt`. (When there is no previous or next line for `-` or `+` to match, the script fails.) – chepner Aug 26 '21 at 12:27
1 Answers
0
This is a most inelegant solution, but works. Perhaps, it will anger a UNIX guru to come and provide a real answer.
grep 'Nan' -n -C 1 target_file.txt | awk -F '[-:]' '{print $2}' | sed '2d' | paste -d, - - | sed 's/$/d/' > del_lines.sed && sed -f del_lines.sed target_file.txt > output_file.txt
fyi, The word "perticular" is misspelled, its "par-" like in golf!

dannylee8
- 505
- 7
- 17