Skip to content

sed -i treats multiple files as one continuous stream #567

Closed

Description

@SichenLiang

When -i is used with multiple input files, uutils sed carries its processing state across file boundaries. Line numbers continue across files, $ matches only the end of the last file, and commands such as N can move output from one file into another.

GNU sed processes each file separately when -i is used.

The following was reproduced with GNU sed 4.10 and uutils sed built from cffecd15, both under LC_ALL=C. I use -i -e because uutils otherwise interprets the following argument as the backup suffix, as reported in #165.

For example, $d should remove the last line of each file:

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ sed -i -e '$d' f1 f2; cat f1; echo --; cat f2
a1
a2
--
b1
b2

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ ./target/release/sed -i -e '$d' f1 f2; cat f1; echo --; cat f2
a1
a2
a3
--
b1
b2

Line numbers do not restart at the second file either:

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ sed -i -e = f1 f2; cat f2
1
b1
2
b2
3
b3

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ ./target/release/sed -i -e = f1 f2; cat f2
4
b1
5
b2
6
b3

The same state carries across the boundary when N reads the next line. Here, the last line of f1 is written into f2:

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ sed -i -e 'N;s/\n/+/' f1 f2; cat f1; echo --; cat f2
a1+a2
a3
--
b1+b2
b3

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ ./target/release/sed -i -e 'N;s/\n/+/' f1 f2; cat f1; echo --; cat f2
a1+a2
--
a3+b1
b2+b3

Adding -s makes both uutils commands match GNU. With -n, however, N still reads across the boundary under -s:

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ sed -n -s -e 'N;s/\n/+/;p' f1 f2
a1+a2
b1+b2

$ printf 'a1\na2\na3\n' > f1; printf 'b1\nb2\nb3\n' > f2
$ ./target/release/sed -n -s -e 'N;s/\n/+/;p' f1 f2
a1+a2
a3+b1
b2+b3

The GNU sed manual says of -i: "This option implies -s." And of line number addresses: "Note that sed counts lines continuously across all input files unless -i or -s options are specified."

In src/sed/mod.rs, separate is enabled by --separate but not by --in-place. The per-file handling in src/sed/processor.rs relies on that flag.

I have a patch and can open a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions