5

Given the following files

$ ls bar.txt baz.txt qux.txt 

I would like to save only the first txt file to a variable. I tried this

$ var=*.txt 

but it just saves all files

$ echo $var bar.txt baz.txt qux.txt 

I would like to do this using a wildcard if possible, and extglob is okay. The files here do not have spaces in the name but I would like the solution to also work for files with spaces.

After using kamituel’s answer I realized that this can work too

$ set *.txt $ echo $1 bar.txt 

3 Answers 3

9

Use this:

$ var=(*.txt) $ echo $var bar.txt 

Key here is to use parentheses - putting elements into array. So echo $var prints the first element from the array (bar.txt). You can see that by printing the whole array:

$ echo ${var[@]} bar.txt baz.txt qux.txt 
Sign up to request clarification or add additional context in comments.

1 Comment

You may need shopt -s nullglob before var=( *.txt ) in case there are no *.txt files.
0

You can (slightly) abuse the for statement to set the variable:

$ for var in *.txt; do break; done $ echo $var bar.txt 

On the plus side, var only contains the name of the first file, not everything matching the pattern. On the minus side, this is more verbose than the array solution that kamituel gives, and the overhead of storing all matching files is unlikely to be an issue in real life.

1 Comment

This actually was interesting, but so evil for the "next guy", it's hard to endorse it. :)
0
$ touch "test file1.txt" $ touch "test file2.txt" $ var=`ls *.txt | head -1` $ echo $var test file1.txt` 

This will return the first file.

To find the last one, either do "ls -r" instead of "ls" or "tail -1" instead of "head -1".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.