How to add a character after the first word/space on each line?

Hi:)

I have a large file ( couple thousand lines ) and I'm trying to add a character after the first word/space on each line.
eg:

First line of text
Second line of text
Third line of text
Fourth line of text
Fifth line of text

I'd like to accomplish:

First - line of text
Second - line of text
Third - line of text
Fourth - line of text
Fifth - line of text

Thanks a lot!

Hello martinsmith,

Could you please try following and let me know if this helps you.

awk '{$2="-" OFS $2} 1'  Input_file

Output will be as follows.

First - line of text
Second - line of text
Third - line of text
Fourth - line of text
Fifth - line of text
 

Thanks,
R. Singh

1 Like

:b: Thank you R. Singh. It works perfectly as i needed. Cheers

Assuming that there is at least one space (or two words) on each line, you could also try the simpler:

sed 's/ / - /' file
1 Like

Your Welcome, also if you have blank lines too into your Input_file and you want to leave them as it is, then following may help you. Let's say following is the Input_file:

First line of text
Second line of text
Third line of text
Fourth line of text

Fifth line of text
awk 'NF{$2="-" OFS $2} 1'  Input_file

Output will be as follows.

First - line of text
Second - line of text
Third - line of text
Fourth - line of text

Fifth - line of text

Thanks,
R. Singh

1 Like

Thank you Don and R. Singh. The commands work perfectly as i was hoping to solve my problem. Thanks for the blank lines solution as well. Cheers

what if we want to use it after second word.
thanks in advance.

Try:

sed 's/ / - /2' file

Note that this also leaves lines that don't have two <space> characters in them unmodified.

1 Like

Hello bhupeshchavan,

Adding an awk solution for same now too.

awk '{$2=$2 FS "-"} 1'  Input_file

If you need to remove any empty lines from Input_file then following may help you in same.

awk 'NF{$2=$2 FS "-"} 1'  Input_file

Thanks,
R. Singh

1 Like