2

I want to add the following to the file /etc/securetty using sed:

pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

I wrote the following command for this purpose:

sed -i '$a pts/0\\npts/1\\npts/2\\npts/3\\npts/4\\npts/5\\npts/6\\npts/7\\npts/8\\npts/9' /etc/securetty

which gives me the output:

pts/0\npts/1\npts/2\npts/3\npts/4\npts/5\npts/6\npts/7\npts/8\npts/9

I'm clearly missing out on something here. What could be wrong in my sed command?

3

3 Answers 3

6

Simple shell approach:

for i in {0..9}; do echo "pts/"$i; done >> /etc/securetty

>> - to append output to the file

> - to direct output to the file(overwriting)

1
4

By the way , If you want to append to the end of an existed file something like this, you don't need neither sed nor a shell loop. It is just one command:

$ printf '%s\n' "pts/"{0..10} >> /etc/securetty

If you want to insert in the beginning of the file you can still do it with printf:

$ cat file1
europe|EU
australia|AU
china|CN
$ printf '%s\n%s\n' "pts/"{0..10} "$(<file1)"
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9
pts/10
europe|EU
australia|AU
china|CN

You can replace the contents of your file /etc/securetty like this (even sed -i does exactly the same job behind the scenes):

$ printf '%s\n%s\n' "pts/"{0..10} "$(</etc/securetty)" > tmpsecure && mv -f tmpsecure /etc/securetty

Alternative:

$ { printf '%s\n' "pts/"{0..10}; cat /etc/securetty; } > tmpsecure && mv -f tmpsecure /etc/securetty
# Or
# cat <(printf '%s\n' "pts/"{0..10}) /etc/securetty > tmpsecure && mv tmpsecure /etc/securetty
1
  • 1
    +1 for the best approach here, imo. And for those on very old systems, they can replace "$(<file1)" with "$(cat file1)" Apr 14, 2017 at 14:00
2

It should be:

sed -i 'a pts/0\npts/1\npts/2\npts/3\npts/4\npts/5\npts/6\npts/7\npts/8\npts/9' /etc/securetty

Alternatively, you can put the contents into a file and use the read (r) option of sed to append to the target file.

Example:

$ cat input.txt
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

$ cat /etc/securetty
This is a dummy file

Command:

sed -i 'r input.txt' /etc/securetty

The file /etc/securetty is modified as below:

$ cat /etc/securetty
This is a dummy file
pts/0
pts/1
pts/2
pts/3
pts/4
pts/5
pts/6
pts/7
pts/8
pts/9

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