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

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
  • 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? – Arijit Banerjee Apr 25 '18 at 4:14
  • @ArijitBanerjee Yes, that is not surprising. Why would you want to change the quotes? – Kusalananda Apr 25 '18 at 4:27
  • Changed because I was getting sed: -e expression #1, char 1: unknown command: '' ` – Arijit Banerjee Apr 25 '18 at 4:52
  • @ArijitBanerjee What Unix shell are you trying to run this in? – Kusalananda Apr 25 '18 at 4:54
  • I am using Gow (Gnu On Windows) and from its documentation I can see it supports bash & zsh – Arijit Banerjee Apr 25 '18 at 4:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.