Select the nth file in the folder (using sed)?

I am trying to select the nth file in a folder whose file name matches a specific pattern:

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

but it returns the 3rd line of the first matching file.

I also tried sed -n 3p ls /path/to/files/*pattern*.txt which also does not work.

Thank!

+4
source share
2 answers

Why sed when bash is much better?

Assuming some name nindicates the index you need:

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"

sed , , , , , , .

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

, ls.

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

, patterne

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

, ,

0

Source: https://habr.com/ru/post/1530297/


All Articles