0

I have a text file test.txt with something like the following:

foo
configure
top
start
fun
bar
hello

I want to comment out line numbers 2, 5 and 7, so that the output would look like:

foo
#configure
top
start
#fun
bar
#hello

When I use sed -i "2,7 {s/^/#/}" test.txt lines 2, 3, 4, 5, 6 and 7 get commented. How to ensure only specific line numbers are commented? Appreciate any help.

1 Answer 1

1

With 2,7 you specify a range of lines to apply the expression on. In this case, you just want to pick three specific lines.

sed -e '2s/^/#/' -e '5s/^/#/' -e '7s/^/#/'  file

or with the actual commenting-out operation separated out into a single place in he sed editing code (only really useful if you need to do something that would be more complicated than just adding a # to the start of the line):

sed -e 2bc -e 5bc -e 7bc -e b -e :c -e 's/^/#/' file

The b command branches to a label (here c, defined with :c) or to the end of the script if no label is given.

or with awk:

awk 'NR == 2 || NR == 5 || NR == 7 { print "#" $0; next } 1'  file
7
  • Thanks for the explanation. The sed works when I change ' to ". But the awk fails with awk: 'NR awk: ^ invalid char ''' in expression 'NR' is not recognized as an internal or external command, operable program or batch file. 'NR' is not recognized as an internal or external command, operable program or batch file.. Can you please suggest why? Apr 25, 2018 at 4:14
  • @ArijitBanerjee Yes, that is not surprising. Why would you want to change the quotes?
    – Kusalananda
    Apr 25, 2018 at 4:27
  • Changed because I was getting sed: -e expression #1, char 1: unknown command: '' ` Apr 25, 2018 at 4:52
  • @ArijitBanerjee What Unix shell are you trying to run this in?
    – Kusalananda
    Apr 25, 2018 at 4:54
  • I am using Gow (Gnu On Windows) and from its documentation I can see it supports bash & zsh Apr 25, 2018 at 4:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .