Chudar
Chudar

Reputation: 394

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"

Upvotes: 1

Views: 12913

Answers (3)

Gilles Quénot
Gilles Quénot

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"

Note :

  • no space allowed around = in shell
  • The backquote
    `
    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

John1024
John1024

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.

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

Upvotes: 5

Mark Lakata
Mark Lakata

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

Related Questions