2

I have file which looks like following:

/usr/local/bin
/bin
/usr/bin
/usr/local/sbin
/usr/sbin
/sbin
/home/user/.local/bin
/home/user/bin
/home/user/perl5/bin

now I want to concatenate the lines by colon using while read syntax, something like this:

cat file | while read data; do path="$path:$data"; done && echo $path

but above code is not working that I am expecting, the $path variable remains empty, what is the problem?

2

2 Answers 2

2

You can get this output doing the following:

$ tr -s '\n' ':' <file
/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/user/.local/bin:/home/user/bin:/home/user/perl5/bin

It replaces all new lines with a colon.

Regarding the error in your syntax, note that the proper syntax is:

while read data
do
   ... things ...
done < file
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the loop syntax. +0 for the tr command - it indeed replaces all newlines with a colon, including the last, which produces an unwanted trailing colon (that is missing from the above output).
1

We don't need a loop or an external command.

path=$(<file) && path=${path//$'\n'/:} && echo "$path"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.