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:
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
CodePudding user response:
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 which is not needed in this case since echo
's args will start with non space, regardless of how many spaces are trailing.