Linux – AWK and file names with space in it.

awkbashlinux

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 ?

Best Answer

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.