StayFoolish
StayFoolish

Reputation: 521

linux show head of the first file from ls command

I have a folder, e.g. named 'folder'. There are 50000 txt files under it, e.g, '00001.txt, 00002.txt, etc'. Now I want to use one command line to show the head 10 lines in '00001.txt'. I have tried: ls folder | head -1 which will show the filename of the first: 00001.txt But I want to show the contents of folder/00001.txt So, how do I do something like os.path.join(folder, xx) and show its head -10?

Upvotes: 0

Views: 1503

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295403

The better way to do this is not to use ls at all; see Why you shouldn't parse the output of ls, and the corresponding UNIX & Linux question Why not parse ls (and what to do instead?).

On a shell with arrays, you can glob into an array, and refer to items it contains by index.

#!/usr/bin/env bash
#              ^^^^- bash, NOT sh; sh does not support arrays

# make array files contain entries like folder/0001.txt, folder/0002.txt, etc
files=( folder/* )  # note: if no files found, it will be files=( "folder/*" )

# make sure the first item in that array exists; if it does't, that means
# the glob failed to expand because no files matching the string exist.
if [[ -e ${files[0]} || -L ${files[0]} ]]; then
  # file exists; pass the name to head
  head -n 10 <"${files[0]}"
else
  # file does not exist; spit out an error
  echo "No files found in folder/" >&2
fi

If you wanted more control, I'd probably use find. For example, to skip directories, the -type f predicate can be used (with -maxdepth 1 to turn off recursion):

IFS= read -r -d '' file < <(find folder -maxdepth 1 -type f -print0 | sort -z)
head -10 -- "$file"

Upvotes: 1

user1934428
user1934428

Reputation: 22225

If you invoke the ls command as ls "$PWD"/folder, it will include the absolute path of the file in the output.

Upvotes: 0

Ashwani Tanwar
Ashwani Tanwar

Reputation: 171

Although hard to understand what you are asking but I think something like this will work:

head -10 $(ls | head -1)

Basically, you get the file from $(ls | head -1) and then print the content.

Upvotes: 0

Related Questions