Chudar Chudar - 1 month ago 13
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

#!/bin/sh
value_1=`cat file_1.txt`
value_2=`cat file_2.txt`
value_3 = paste $value_1 $value_2
echo "$value_3"

Answer

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.

Improvement

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")

Example

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