Modify text file using shell script

Hi,

I have a text file which is following format -

COL VAL
ABC 1
ABC 2
ABC 3
ABC 4
ABC 5

My requirement is to search for a particular value (provided by user) in the file and comment the previous entries including that as well.

E.g. If I search for number 3, then the output file should be similar to -

COL VAL
#ABC 1
#ABC 2
#ABC 3
ABC 4
ABC 5

Kindly suggest with some options. Thanks for your time.

if 'val' is a unique field.

kent$  echo "ABC 1
ABC 2
ABC 3
ABC 4
ABC 5"|awk 'BEGIN{a=1}{print (a)? "#"$0:$0; if($2==3)a=0}'
#ABC 1
#ABC 2
#ABC 3
ABC 4
ABC 5

However if the values are not unique and not sorted, you can use the following:

echo "ABC 1
ABC 2
ABC 3
ABC 4
ABC 5" | awk '{if ($2 <= 3) {print "#"$0} else {print $0}}'

Works as well with:

echo "ABC 1
ABC 2
ABC 3
ABC 4
ABC 5
ABC 4
ABC 2" | awk '{if ($2 <= 3) {print "#"$0 } else {print $0}}'
$ echo "ABC 1
ABC 2
ABC 3
ABC 4
ABC 5
ABC 4
ABC 2" | sed '/ [123]$/s/.*/#&/'
#ABC 1
#ABC 2
#ABC 3
ABC 4
ABC 5
ABC 4
#ABC 2

Doesn't work with values greater than 10 though. If only sed supported if statements ...

which range of value do you need to match ?

or which values do you need to match ?

---------- Post updated at 07:27 PM ---------- Previous update was at 07:14 PM ----------

$ cat tst
ABC 1
ABC 2
ABC 3
ABC 4
ABC 5
ABC 1
ABC 6
ABC 2
ABC 3
ABC 4
ABC 5
ABC 6
$ a=3
$ nawk -v N="$a" '$NF<=N{printf "#"}1' tst
#ABC 1
#ABC 2
#ABC 3
ABC 4
ABC 5
#ABC 1
ABC 6
#ABC 2
#ABC 3
ABC 4
ABC 5
ABC 6

Thank you everyone for responding to my question. Specially to "ctsgnb" as the solution he provided worked perfectly in my scenario.

Thanks again :slight_smile: