Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash file variable issue

edit: solved, put echo in front of $1

The bash file created is supposed to take in a sentence as an argument/input/whatever it’s called, save it to a variable, and then make a variable where that’s just a string of the first letters of every word, and finally print it out.

example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sh test.sh 'i like that dog'
iltd

instead I get nothing.

I am new to bash scripting and here’s what I have

#!/bin/bash
name=$($1 | sed -e 's/$/ /' -e 's/\([^ ]\)[^ ]* /\1/g' -e 's/^ *//')
echo $name

Whatever I’m doing wrong is far above me. Any help and explanation would be much appreciated

>Solution :

You are missing echo there. This seems to work well:

#!/bin/bash
name=$(echo $1 | sed -e 's/$/ /' -e 's/\([^ ]\)[^ ]* /\1/g' -e 's/^ *//')
echo $name

How does it works?

The echo command take the args from $1 echo send it to the standard output which is redirected by | to sed‘s standard input. The first sed expression s/$/ / is appending a space at the end, which is needed for the next expression, s/\([^ ]\)[^ ]* /\1/g in which \([^ ]\) is the first non-space char to be saved in \1 and [^ ]* are all the non-space chars to be replaced with whatever is in \1 and /g means do it for all, or don’t stop after one match. The last expression is to drop the spaces at the beginning.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading