madieke
madieke

Reputation: 155

select nth file in folder (using 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!

Upvotes: 5

Views: 4933

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

ls -1 /path/to/files/*pattern*.txt  | sed -n '3p'

or, if patterne is a regex pattern

ls -1 /path/to/files/ | egrep 'pattern' | sed -n '3p'

lot of other possibilities, it depend on performance or simplicity you look at

Upvotes: 0

kojiro
kojiro

Reputation: 77059

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.

Upvotes: 9

Related Questions