Chudar Chudar - 3 years ago 157
Bash Question

Using paste command inside shell script

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

value_1=`cat file_1.txt`
value_2=`cat file_2.txt`
value_3 = paste $value_1 $value_2
echo "$value_3"

Answer Source

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


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
$ cat file2

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download