Mark Scheck
Mark Scheck

Reputation: 119

Using Sed to extract the headers in multiple files

I used head -3 to extract headers from some files that I needed to show header data I did this:

head -3 file1 file2 file3 

and head -3 * works also.

I thought sed 3 file1 file2 file3 would work but it only gives the first file's output and not the others. I then tried sed -n '1,2p' file1 file2 file3. Again only the first file produced any output. I also tried with a wildcard sed -n '1,2p' filename* same result only the first file's output.

Everything I read seems like it should work. sed *filesnames*.

Thanks in advance

Upvotes: 1

Views: 1082

Answers (1)

Sundeep
Sundeep

Reputation: 23677

Assuming GNU sed as question is tagged linux. From GNU sed manual

-s --separate By default, sed will consider the files specified on the command line as a single continuous long stream. This GNU sed extension allows the user to consider them as separate files: range addresses (such as ‘/abc/,/def/’) are not allowed to span several files, line numbers are relative to the start of each file, $ refers to the last line of each file, and files invoked from the R commands are rewound at the start of each file.

Example:

$ cat file1
foo
bar
$ cat file2
123
456

$ sed -n '1p' file1 file2
foo
$ sed -n '3p' file1 file2
123
$ sed -sn '1p' file1 file2
foo
123


When using -i, the -s option is implied

$ sed -i '1chello' file1 file2
$ cat file1
hello
bar
$ cat file2
hello
456

Upvotes: 3

Related Questions