Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Lets say I have strings like this:


and I want to create a loop to echo


After some research I found out that the cut command is not abled to do so. I think awk might be an option but I did not fully understand how to get it working properly on this example... so any help would be very appreciated.

share|improve this question
up vote 2 down vote accepted

I think that the simplest way is to use string operators. For example, if:


then you can use somethink like:

echo ${str%.txt}

But, you can still use cut with the help of rev (see man cut and man rev for more info):

echo $str | rev | cut -d/ -f1 | cut -d. -f 2- | rev

And the solution using awk is:

echo $str | awk -F/ '{print $NF}' | awk -F. '{$NF=""}1'
share|improve this answer
awesome. thank you. returns: my_first_text.txt ... any way to further cut of the ".txt"? And can you give me a hint how the syntax for the first example works? – Joschi Jan 22 '14 at 14:02
@Joschi I updated my answer. If you want to cut .txt, you can use for example: echo ${str##*/} | awk -F. '{$NF=""}1' – Radu Rădeanu Jan 22 '14 at 14:12
works perfect! Thanks!! – Joschi Jan 22 '14 at 14:15
@Joschi Just now I sow in your question that you didn't want .txt at the end. So, I just edited again my answer. – Radu Rădeanu Jan 22 '14 at 14:33

To avoid using any external programs such as cut or awk, you can sort-of concatenate bash string operators e.g. if str="/somefolder/andsubfolder" then

str="${str##*/}"; echo "${str%.txt}"

removes first the leading path component (longest prefix matching */) then removes the .txt suffix (shortest suffix matching *.txt)

You could also do

str="${str##*/}"; echo "${str%.*}"

to remove any single .* suffix instead of just .txt

share|improve this answer

try this out shell script


my_file=$(echo $abc | awk -F/ '{print $4}')
echo "$my_file"

this will sure help you.

share|improve this answer
Have you tested your "solution"? – Radu Rădeanu Jan 24 '14 at 6:30
#!/bin/bash abc=/somefolder/andsubfolder/my_first_text.txt my_file=$(echo $abc | awk -F/ '{print $4}') echo "$my_file"sorry i havent tested so i am now correcting it please run this – smn_onrocks Jan 24 '14 at 6:34
No dice, still -1 ... – Radu Rădeanu Jan 24 '14 at 6:35
ok.. but now i have run the sh file in my system. where is my mistake if you will let me know that would be very kind.. – smn_onrocks Jan 24 '14 at 6:37
hello sir Radu Rădeanu will you please tell me what is my mistake in my updated script.. if you tell me i can improve my future script.. – smn_onrocks Jan 24 '14 at 6:43

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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