Modifying a particular line in a text file from the command-line

Viewed 1356

I have a text file "text.txt", it contains a bunch of lines with text (or empty lines).

I am trying to form a single sed/awk command-line command that will let me comment out any like (by adding a "#" to the start of whatever line number I specify).

For example, the text file might look like: A B C D and I want to issue a command that specifies line number 2, so it will look like: A #B C D If it's possible to specify a range of lines, so multiple lines could be modified, like "2-4" or 2,3,4" that would help, too.

I've found conflicting (to me) information about the -n and -e options in sed, and just can't quite get it to work as I hoped. I'm using Kubuntu 18.04.

Any suggestions? Thanks.

I've been stringing concepts together that I found in other questions, like having to keep the line, but add "#" to the start of it, so I've got "s/(.*)/#$1/" as the back substitution.

I thought it might work as: sed '2,4!s/(.)/#$1/' text.txt However, I get s/.: Event not found. This seemed to have some good parts to it, however, it didn't quite work as I hoped, and it only deals with one line, not all lines cat text.txt | sed -n '2{s/(.)/#$1/;p}'

2 Answers

This should be a task for awk. In this solution creating a variable names lines which will having line numbers in it whichever you want to change(comma separated), just mention any number of line numbers with comma separated values in it and that should do the trick here. Tested it successfully on https://ideone.com/ajnNSU

awk -v lines="2,3,4" '
BEGIN{
  num=split(lines,array,",")
  for(i=1;i<=num;i++){
    linechange[array[i]]
  }
}
FNR in linechange{
  $0="#" $0
}
1
' Input_file

A simple sed substitute will also work given the line number, e.g.

sed -i '2s/^/# /' file

The above will edit file in place commenting line 2 inserting "# " at the beginning of the line. To pass in the line number as an argument, double-quote the expression, e.g.

#!/bin/bash

sed -i "$1s/^/# /" "$2"

Will take the line number as the first argument and the file to comment as the second and edit the file in-place making the comment. You should validate the first argument is an integer and that the second is a file that exists and is non-empty. If you save the script as cmt and make it executable (e.g. chmod +x cmt), then you would comment the 2nd line in file as:

./cmt 2 file
Related