user1701545
user1701545

Reputation: 6190

cat with output of sed

I'd like to delete all lines starting with ## in a file (file.a) and replace them with all the lines of another file (file.b). The lines to be deleted from file.a appear first in that file (there are no lines preceding them).

The long way would be:

sed -i '/##/d' file.a
cat file.b file.a > file.c
mv file.c file.a

Is there a short (in line) way?

Upvotes: 0

Views: 1104

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52112

For example files file.a

## line
## line
## line
linea1
linea2
linea3

and file.b

lineb1
lineb2
lineb3

This should do it:

$ sed -e '1r file.b' -e'/^##/d' file.a
lineb1
lineb2
lineb3
linea1
linea2
linea3

The r filename command inserts a file on line 1, and the second command removes all the lines starting with ##. They have to be in separate -e expressions because after the filename there has to be a newline or the end of a command, so this would work as well:

sed '1r file.b
/^##/d' file.a

For in-place modification of file.a, the command becomes

sed -i -e '1r file.b' -e'/^##/d' file.a

Notice that the order of commands is significant: a delete command (d) starts a new cycle, and any command that comes after it is skipped, so r has to go first. Hat-tip: potong

Upvotes: 1

Related Questions