octosquidopus
octosquidopus

Reputation: 3713

sed: How to insert before and after every line?

I'm trying to figure out how to insert text before and after every line in a text file using sed on OS X, but something is obviously wrong with my approach.

This is what I have:

sed 's/\(^\).\($\)/A \1\2 Z/g' input

This is what I want:

input:

bbb

ccc
ddd

output:

A bbb Z

A ccc Z
A ddd Z

EDIT: Also, don't match blank lines (or those containing only spaces).

Upvotes: 1

Views: 561

Answers (2)

UlfR
UlfR

Reputation: 4395

You could use:

sed 's/.*/A \0 Z/' input
  • .* will match the full line
  • \0 will past the full thing from the first expression

Upvotes: 1

anubhava
anubhava

Reputation: 784888

You can use:

sed 's/.*/A & Z/' file
A bbb Z
A ccc Z
A ddd Z

& is back-reference of complete match in regex pattern.

Or using awk:

awk '{print "A", $0, "Z"}' file

Upvotes: 2

Related Questions