Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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:


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

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

Output from script is:

11237_712312955_2012-01-04
18_31_03

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

2 Answers 2

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
1  
..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:

#!/bin/bash
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

 
discard

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.