Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select nth file in folder (using sed)?

Tags:

bash

sed

I am trying to select the nth file in a folder of which the filename matches a certain pattern:

Ive tried using this with sed: e.g., sed -n 3p /path/to/files/pattern.txt

but it appears to return the 3rd line of the first matching file.

Ive also tried sed -n 3p ls /path/to/files/*pattern*.txt which doesnt work either.

Thanks!

like image 230
madieke Avatar asked Mar 05 '14 19:03

madieke


1 Answers

Why sed, when bash is so much better at it?

Assuming some name n indicates the index you want:

Bash

files=(path/to/files/*pattern*.txt)
echo "${files[n]}"

Posix sh

i=0
for file in path/to/files/*pattern*.txt; do
  if [ $i = $n ]; then
    break
  fi
  i=$((i++))
done
echo "$file"

What's wrong with sed is that you would have to jump through many hoops to make it safe for the entire set of possible characters that can occur in a filename, and even if that doesn't matter to you you end up with a double-layer of subshells to get the answer.

file=$(printf '%s\n' path/to/files/*pattern*.txt | sed -n "$n"p)

Please, never parse ls.

like image 66
kojiro Avatar answered Sep 24 '22 05:09

kojiro