locke
locke

Reputation: 85

How to append new lines of text to the end after cat'ing multiple line file into variable

I have a file with contents like this:

aaa bbb
ccc ddd
eee fff

If I cat the file into a variable:

var=`cat file.txt`

I can echo the contents like this:

echo $var
aaa bbb ccc ddd eee fff

Or like this, with the newlines preserved:

echo "$var"
aaa bbb
ccc ddd
eee fff

I want to add new lines of text to the variable $var, so that when I write $var back out to a file:

echo "$var" > newfile.txt

The contents of newfile.txt will have my new lines at the end:

var2=`cat newfile.txt`
echo "$var2"
aaa bbb
ccc ddd
eee fff
ggg hhh
iii jjj

I cannot figure out how to do this. Thanks.

Upvotes: 0

Views: 3829

Answers (4)

chepner
chepner

Reputation: 531055

$ var2=$(< file.txt)
$ var2+=$'ggg hhh\niii jjj\n'
$ echo "$var2" > newfile.txt
$ cat new file.txt
aaa bbb
ccc ddd
eee fff
ggg hhh
iii jjj

The += operator can be used to append values to the end of an existing parameter. You could also forgo modifying the value of var2, and simply write your additional data like this:

$ var2=$(< file.txt)
$ { echo "$var2"
>   printf "%s\n" "ggg hhh" "iii jjj"
> } > newfile.txt

Some updates to avoid bash extensions.

  1. $(< file.txt) is a more-efficient implementation of the standard $(cat file.txt).
  2. $'...' is not supported by dash, but embedded newlines should still work:

    var2="$string1
    $string2"
    
  3. printf "%s\n" "$string1" "$string2" should work fine in dash.

Upvotes: 1

William Pursell
William Pursell

Reputation: 212238

Rather than making the assignment and then appending data to the variable, just do what you want when you make the initial assignment:

var=$( cat file.txt; echo ggg hhh; echo iii jjj; )

or

var=$( cat file.txt - << EOF
ggg hhh
iii jjj
EOF
)

Upvotes: 2

rojomoke
rojomoke

Reputation: 4015

$ var="$var
> xxx yyy
> zzz ggg"

$ echo $var
aaa bbb
ccc ddd
eee fff
xxx yyy
zzz ggg

Upvotes: 1

phyrrus9
phyrrus9

Reputation: 1467

You just echo it in append mode

echo "$var" >> newfile.txt

the >> means it won't open the file in plain write mode. It opens in O_RDRW | O_APPEND

Upvotes: -1

Related Questions