Server Fault is a question and answer site for system and network administrators. 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

I'm trying to parse files with awk to change their names. Everything went well until im started to do this with files with space in file name. File names are something like 11237_712312955_2012-01-04 18_31_03.wav and I want to replace wav from file name. This is example of my code:

ls | awk -F\. '{print $1}'

After i run this in console evething is ok and I get file name whithout extension.

Example: file 11237_712312955_2012-01-04 18_31_03.wav

after ls | awk -F\. '{print $1}' in console I'm geting:

11237_712312955_2012-01-04 18_31_03 and this is correct.

But when I put this in my script:

for i in $(ls);
  FILENAME=echo $i | awk -F\. '{print $1}'; #problematic line 
  echo $FILENAME

Script is splitting file into two in place where space occurred.

Output from script is:


How to make my script work properly ?

share|improve this question
Rename your files to remove the spaces. Seriously. Spaces no more belong in filenames than tattoos belong on the lower back. – Tom O'Connor Apr 3 '12 at 6:38
Yup I know that. I removed the spaces after conevrting and rename files. – B14D3 Apr 3 '12 at 10:06
up vote 11 down vote accepted

The issue here is parsing with ls. Consider to take a look here: Why you shouldn't parse the output of ls.

The reason why you shouldn't do it is since UNIX allows almost any character in a filename, including whitespace, newlines, commas, pipe symbols, and pretty much anything else you'd ever try to use as a delimiter except NUL. In its default mode, if standard output isn't a terminal, ls separates filenames with newlines. This is fine until you have a file with a newline in its name.

share|improve this answer
..well, yes, that - and the fact that he's perpetrating half a dozen egregious offenses aginst bash scripting :) – adaptr Apr 2 '12 at 9:30
Your link was very helpful. Thank you very much. – B14D3 Apr 2 '12 at 10:20
@B14D3 You are very welcome. Please accept if the answer suits you. :) – Eugene S Apr 2 '12 at 10:29

Oh my god, that's awful.

Your script uses bash; I suggest you do this instead:

for i in *.wav; do mv "${i}" "${i%.wav}.ext"; done

See the Bash Guide for more details on parameter expansion.

share|improve this answer

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.