Reputation: 394
I have 3 text files. I would like to read them and store them in different variables and later concatenate them using paste and print them in console. I tried the following code but it threw an error saying
File not found
Here is my code
#!/bin/sh
value_1=`cat file_1.txt`
value_2=`cat file_2.txt`
value_3 = paste $value_1 $value_2
echo "$value_3"
Upvotes: 1
Views: 12913
Reputation: 185015
#!/bin/sh
value_1=$(cat file_1.txt
value_2=$(cat file_2.txt)
value_3=$(echo $value_1 $value_2 | paste) # or value_3="$value1 $value2"
echo "$value_3"
=
in shell`is used in the old-style command
substitution, e.g.
foo=`command`
The foo=$(command)
syntax is recommended instead. Backslash handling inside $()
is less surprising, and $()
is easier to nest.
Check http://mywiki.wooledge.org/BashFAQ/082
Upvotes: 0
Reputation: 113814
paste
expects its arguments to be the names of files, not the content of files. With bash, ksh, or zsh, there is a way around this. Replace:
paste $value_1 $value_2
with:
paste <(echo "$value_1") <(echo "$value_2")
<(...)
is called process substitution. It makes the output from the command inside the parens look like a file.
If we don't know the first character in the output, then printf
is more reliable than echo
:
paste <(printf "%s" "$value_1") <(printf "%s" "$value_2")
Let's use these two test files:
$ cat file1
1
2
$ cat file2
a
b
Now, let's read those files into variables and apply paste to those variables:
$ value_1=$(cat file1); value_2=$(cat file2)
$ paste <(printf "%s" "$value_1") <(printf "%s" "$value_2")
1 a
2 b
Or, saving the output in a variable:
$ value_3=$(paste <(printf "%s" "$value_1") <(printf "%s" "$value_2"))
$ echo "$value_3"
1 a
2 b
Upvotes: 5
Reputation: 20818
The third line should read
value_3=`paste file_1.txt file_2.txt`
You need the backticks, no space after value_3
and don't use the variables as arguments, use the file names.
The reason it is saying "file not found" is because the value_3
with a space after it is being interpreted as a command to be run.
Upvotes: 0