Question: I have some files I downloaded recently and I want to name. It is possible to do something like: 

```
rename 's/ /_/g' $(ls -t | head -n5) 

```

Actually, I would like to rename last downloaded 5 files.

Any idea?

Answer: 
As already pointed out, [parsing `ls` is fragile](http://mywiki.wooledge.org/ParsingLs). It will break if your file names have any type of weirdness (spaces, newlines, control characters etc). Since you want to replace spaces with `_`, your suggested approach will fail. A safe way to do this would be:

```
stat --printf '%n/%Y\0' * | sort -rz -t'/' -k 2 | head -z -n 3 | 
    cut -d'/' -z -f 1 | xargs -0 perl-rename 's/ /_/g'

```

* `stat --printf '%n/%Y\0' *` : this will print out the name (`%n`) of every file or directory in the current directory followed by a slash (`/`; I am using a slash since that is not allowed in a file name so can safely be used as a separator) and the file's modification time in seconds since the epoch (`%Y`) and finally a NULL character (`\0`).
* `sort -rz -k 2` : this will take NULL-separated input (`-z`) and sort it in reverse order (`-r`) based on the value in the second `/`-separated (`-t'/'`) field of each line (`-k 2`).
* `head -z -n 5` : keep the first 5 (`-n 5`) null-separated (`-z`) lines.
* `cut -d'/' -z -f 1` : print the 1st (`-f 1`) `/`-separated (`-d /`) field of null-delimited (`-z`) data.
I just gave `ls -q` a try:

```
IFS='
'
for file in `ls -tr1q|tail -n5`; do
  rename 's/ /_/g' "$file"
done

```

Does the desired rename, even for filenames with newline or other control characters, although it gives an error:

```
Unsuccessful stat on filename containing newline at /usr/bin/rename line 59

```

(with perl v5.20.2)