zBase=$(basename "{query}")
echo -n $title;

The above command copies the filename to the clipboard (using Alfred: the {query} part is from Alfred). Now, I want to copy only the first word of the filename. How can I modify it?

Here is an example filename:

John 2015 Noun and verb structure.pdf

The above commend gives me [John 2015 Noun and verb structure] in my clipboard. Now, I want to get only John in my clipboard.

  • “The above commend gives me [John 2015 Noun and verb structure] in my clipboard.” — no it does not, in so many ways it does not. It look like you were working to two things at once, and put them both into this question, as I see no relation ship between the code above and this statement. – ctrl-alt-delor Jun 1 '17 at 21:17
  • when you define zBase you could take the output of the basename and pipe it through cut using the -d option (delimiter) and specify a space as the delimiter - see this for an example - gist.github.com/anonymous/4d2d7261588a69fc7779511d3e50e3d6 – ivanivan Jun 1 '17 at 21:26

Instead of using external tools like sed, cut or awk, you can simply use the shell's build-in variable expansion that you already used for removing the extension:

echo -n ${title%% *}

Using double %% means remove the longest match, so you remove everything from the variable starting with the first whitespace.

| improve this answer | |
  • Wow, that is great. It worked perfectly. Thank you. – Dellu Jun 3 '17 at 1:51
title=$(echo $title | cut -d" " -f1)

Add this before echo. It cut's the name at every space and takes the first part -> What you wanted to do

| improve this answer | |
  • thank you. Yes, this also worked perfectly. – Dellu Jun 3 '17 at 1:53

Here you go, title=$(echo $zBase|awk {'print $1'})

In awk $1 gives the first word, $2 2nd word and so on.

| improve this answer | |

You can always rely on any text processing tool to do the job. Say sed for instance:

$ sed -r 's/^([[:alpha:]]*).*/\1/' <<< "John 2015 Noun and verb structure.pdf"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.