Reputation: 85
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
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.
$(< file.txt)
is a more-efficient implementation of the standard $(cat file.txt)
.$'...'
is not supported by dash
, but embedded newlines should still work:
var2="$string1
$string2"
printf "%s\n" "$string1" "$string2"
should work fine in dash
.Upvotes: 1
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
Reputation: 4015
$ var="$var
> xxx yyy
> zzz ggg"
$ echo $var
aaa bbb
ccc ddd
eee fff
xxx yyy
zzz ggg
Upvotes: 1
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