0

I have to build a bash script that removes upper and lower lines from a file.

The script ask the person for a word, searches the word in the file and removes 4 upper lines, 9 lower lines and the line that contains the word.

Bellow are the commands that works:

vi -e -c 'g/word/.-4,-d' -c 'wq' fileName

sed -i '/word/,+9d' fileName

The problem is that I want to ask the user for a word that I will use as a variable to do all that.

The bellow code doesn't work!

#!/bin/bash

read -p "Insert the word:" word

vi -e -c 'g/$word/.-4,-d' -c 'wq' fileName

sed -i '/$word/,+9d' fileName

What should I do to solve it?

vallen
  • 9
  • 1
  • 1
    Does https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash answer you question? – KamilCuk May 07 '21 at 20:34

2 Answers2

1

something like this will work, assumes the search word appears only once in the file

$ awk -v b=4 -v a=9 -v word="$word" 'NR==FNR{if($0~word) n=NR; next} 
                                     FNR<n-b || FNR>n+a' file{,}

double scans the file, first to find the line number of the match, second round prints out the lines based on before/after context set.

Also doesn't handle if the search word not found. If you want to print everything add !n || to the last condition

karakfa
  • 66,216
  • 7
  • 41
  • 56
0

You can do it one shot with vi or ed, no need to use sed. Variables inside single quotes won't be interpolated, you need double quotes for that. See Difference between single and double quotes in Bash for details.

vi -e -c 'g/'"$word"'/.-4,+9d' -c 'wq' fileName

printf '/%s/\n-4,+9d\nwq\n' "$word" | ed -s fileName > /dev/null

I don't know ed enough to prevent the line matching the given word from being printed, hence the use of /dev/null

Sundeep
  • 23,246
  • 2
  • 28
  • 103