Search code examples
bashechofilenames

Echo files names within a specific template


I have multiple files starting with the same name within a folder, but there are also other files. Let's say they start with 'plot'. I want to echo the names in such a template

"plot-abc";"plot-dcb";"plot-asd";...

There is no order in the rest of the names. I tried it with

for file in /home/user/*;
do
  echo '"'
  echo ${file##*/}
  echo '";'
done

but this is putting the quotation marks at the very beginning and the end. And can't eliminate the unrelated files.

I'd appreciate if we can find a solution.

Thanks in advance.


Solution

  • printf lets you provide a template, which is repeated as many times as necessary to process all arguments:

    #!/usr/bin/env bash
    #              ^^^^- important: not /bin/sh; bash is needed for array support
    
    shopt -s nullglob                 ## if no files match the glob, return an empty list
    files=( /home/user/plot-* )       ## store results in an array
    
    # if that array is non-empty, then pass its contents as a list of arguments to printf
    (( ${#files[@]} )) && { printf '"%s";' "${files[@]##*/}"; printf '\n'; }