Skip to content
Advertisement

Expanding when one has command substitution

I have to echo an output of a command substitution concatenated with string. The string to be prepended is in fact the string of pathname. The need for use of absolute path together with filename arises due to filename containing special character,-, at the beginning of it. I’ve come up with a draft that only works as planned for the first line of output. How do I expand it to other lines as well?

The example scenario is as provided below.

Inside /tmp directory the files are:

-foo 1.txt
-bar 1.txt

Command and the output is:

$ echo "$PWD/$(ls | grep "^-")"
/tmp/-bar 1.txt
-foo 1.txt

While I want it to be like

/tmp/-bar 1.txt
/tmp/-foo 1.txt

I read about this brace expansion feature but I’m not sure if it works for variables, or command substitution for that matter, as stated here. I also want the separate lines for each files and the filename words unsplitted, which is suggested at when the brace expansion is carried out. (Honestly, I don’t understand much of the literature about the features such as brace expansion!)

Also, are there other more convenient ways to do this? Any help is appreciated.

Advertisement

Answer

To do what you’re asking, getting a list of full paths for files starting with -, you can use readlink:

$ readlink -f ./-*
/tmp/-bar 1.pdf
/tmp/-foo 1.pdf

However, to do directly what you mentioned in comments (using filenames starting with - as arguments for pdfgrep), you can take advantage of the common convention that -- marks the end of options, so everything after it is recognized as a filename:

pdfgrep 'pattern' -- -*

See also POSIX Utility Syntax Guidelines (Guideline 10):

The first -- argument that is not an option-argument should be accepted as a delimiter indicating the end of options. Any following arguments should be treated as operands, even if they begin with the - character.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement