简体   繁体   中英

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).

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

You could use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM