Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file into variable without newlines

Tags:

bash

I am not expert with bash but I would imagine this would be a simple script. I am trying to read a file with a few lines into a single bash variable without the new lines.

My current script reads them in but keeps the presence of newlines

options=$(<vm.options)
echo "$options"

The file looks something like this:

-Random 1
-Letters2
-Occur 3
-In
-Passwords9

The script would read this into a variable where its output would look like:

-Random 1 -Letters2 -Occur 3 -In -Passwords9
like image 827
user0000001 Avatar asked Apr 11 '19 14:04

user0000001


2 Answers

You can do search/replace in bash after reading file content:

options=$(<vm.options)
# replace \n with space
options="${options//$'\n'/ }"

Now examine options variable:

declare -p options

declare -- options="-Random 1 -Letters2 -Occur 3 -In -Passwords9"
like image 50
anubhava Avatar answered Sep 28 '22 00:09

anubhava


This also produces the desired output:

echo "\
-Random 1
-Letters2
-Occur 3
-In
-Passwords9" > tmp

var=$(cat tmp | tr -s '\n' ' ')

echo $var

resulting in:

-Random 1 -Letters2 -Occur 3 -In -Passwords9

the part with cat is not pretty (and may break in specific instances) but it works for this case.

like image 40
Vinicius Placco Avatar answered Sep 28 '22 00:09

Vinicius Placco