-1

I refered this https://unix.stackexchange.com/questions/251388/prefix-and-suffix-strings-to-each-output-line-from-command to add prefix to output of ls.

I want to store this output of ls:

file1
file2
file3

in to a variable with value:

/../file1 /../file2 /../file3

This is my .sh file:

PREFIX="/../"
OUTPUT_INLINE=$(ls | tr "\n" " ")
OUTPUT="${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g"
echo "${OUTPUT_INLINE}"
echo "${OUTPUT}"

Output is:

file1 file2 file3

It means variable OUTPUT contains nothing.

Even if I do:

echo "${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g"

I will get:

/../file1 /../file2 /../file3

What is wrong here ?

Van Tr
  • 5,889
  • 2
  • 20
  • 44

2 Answers2

1
OUTPUT="${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g"

That pipes OUTPUT="${OUTPUT_INLINE}" into sed "s|\<|$PREFIX|g", which doesn’t do anything. I think you meant:

OUTPUT=$(printf '%s' "${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g")

but there’s lots of fragility here around different delimiter types, and you should be able to avoid all that:

PREFIX="/../"

for filename in *; do
    printf '%s%s ' "$PREFIX" "$filename"
done
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

You are assigning OUTPUT variable this command

"${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g"

Which means nothing. Do as you are already doing with OUTPUT_INLINE variable to assign the output of command.

OUTPUT=$(echo -n "${OUTPUT_INLINE}" | sed "s|\<|$PREFIX|g") 
G. C.
  • 387
  • 2
  • 6