Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print first letter of each word in a line

Tags:

bash

sed

awk

I have searched through other posts and have not found an answer that fits my needs. I have a file that is space delimited. I would like to print the first letter of each word in the given line. For example:

cat test.txt
This is a test sentence.

Using either sed, awk, or a combination, I would like the output to be "Tiats". Any advice on pointing me in the right direction?

like image 268
swam Avatar asked Dec 05 '22 22:12

swam


1 Answers

One possibility:

pax> echo 'This is a test sentence.
  This is another.' | sed -e 's/$/ /' -e 's/\([^ ]\)[^ ]* /\1/g' -e 's/^ *//'
Tiats
Tia

The first sed command simply ensures there's a space at the end of each line to simplify the second command.

The second command will strip all subsequent letters and the trailing spaces from each word. A word in this sense is defined as any group of non-space characters.

The third is something added to ensure leading spaces on each line are removed.

like image 135
paxdiablo Avatar answered Jan 01 '23 20:01

paxdiablo