Shell scripting

Asked by Hanen Ben Rhouma

I needed to know which command I can use to take the output of an ls and extract each word from the filename.

Eg: If the output of ls gives...some file name.extension

I want the output as 4 strings some, file, name, extension

The syntax is not very important, I want to know if it can be done at all and (if yes) using which tool/command.

Question information

Language:
English Edit question
Status:
Solved
For:
Ubuntu Edit question
Assignee:
No assignee Edit question
Solved by:
Florian Diesch
Solved:
Last query:
Last reply:
Revision history for this message
Best Florian Diesch (diesch) said :
#1

Use sed and a regular expression:

  ls | sed -e's/[ .]/,/g'

This replaces all spaces and dots with a comma.
See 'man 7 regex ' for more about regular expressions.

Revision history for this message
plutino (plutino) said :
#2

In bash, $IFS denotes the delimiters for word splitting. In your case, just set $IFS=" \t\n.":

#assume you already have the filename in $FN:

OIFS=$IFS #backup old IFS value
IFS=" \t\n."
for word in $FN; do
  something for each token;
done
IFS=$OIFS

Revision history for this message
Hanen Ben Rhouma (hanen105) said :
#3

Thanks Florian Diesch, that solved my question.

Revision history for this message
Hanen Ben Rhouma (hanen105) said :
#4

plutino, your answer is so tricky, I like the concept but confused a little bit about applying it. Can you please give an illustrating example for such variable use?

Thanks in advance :)

Revision history for this message
Florian Diesch (diesch) said :
#5

This just prints all the words:
--------------------------------------------------
OIFS=$IFS
IFS=" \t."

ls | while read line; do
  for token in "$line"; do
    echo $token
  done
done
IFS=$OIFS
--------------------------------------------------

If you want to distinguish between the file names:

--------------------------------------------------
OIFS=$IFS
ls | while read line; do
 echo "$line:"
 IFS=" \t."
 for word in $line; do
   echo " $word"
 done
 IFS=$OIFS
done
--------------------------------------------------