I have this sample file:


For each line, I need to insert a space after the 3rd character of the 4th column, like so:

234234|111||J1X 0H8|SERP||R|D|666|M
234235|222||J1X 0N5|SERP||C||555|M

I've been trying to use the sed and awks commands, but with no positive results. How can I do this?

1 Answer 1


With awk, it's

awk -F '|' -v OFS='|' '{sub(/^.../, "& ", $4); print}' file

But that cannot edit in-place, so you have to:

awk -F '|' -v OFS='|' '{sub(/^.../, "& ", $4); print}' file > "$t" && mv "$t" file

With sed,

sed -i 's/^[^|]*|[^|]*|[^|]*|.../& /' file

If you want to validate the postal code, then

sed -i 's/^\([^|]*|[^|]*|[^|]*|[[:alpha:]][[:digit:]][[:alpha:]]\)\([[:digit:]][[:alpha:]][[:digit:]]|\)/\1 \2/' file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .