3

I have a requirement where if a specific condition is met I need to duplicate the whole content of a file into the same file. Here is the file:

$ cat in.txt
ip
10.22.1.34
10.22.1.35

When a condition is met, for instance

if [[ d=1 ]]; then
copy the file content
fi

the content of the file should be duplicated like below:

ip
10.22.1.34
10.22.1.35
ip
10.22.1.34
10.22.1.35
2
  • @cuonglm, i have update my question May 19, 2016 at 16:47
  • 1
    Why not just cat in.txt in.txt?
    – cuonglm
    May 19, 2016 at 16:49

4 Answers 4

5

You can store file content into variable( it will store newlines) and then append to same file from variable. Just remember to use quotes around variable.

x=$(cat test.txt) && echo "$x" >> test.txt

Or using "tee" command you can append directly to same file, don't get confused when it first shows files original content in stdout, it has same time duplicated actual content of file.

cat test.txt | tee -a test.txt

If you don't want tee's output to be visible you can of course do this:

    cat test.txt | tee -a test.txt > /dev/null
1
  • 2
    For larger files the tee version blows up the file size (not only doubled) Mar 8, 2020 at 18:13
2

You can do something like: cat in.txt > /tmp/tmp.txt && cat /tmp/tmp.txt >> in.txt

0

A cat file.txt >> file.txt should do the trick, >> appends the content of stdout at the end of the specified file

5
  • Have you tried this on a file larger than about 8KB? May 19, 2016 at 18:00
  • Ahah no i didn't, first of all I can't copy a file into itself, and using cat file.txt | xargs -I line echo line >> file.txt, it took a very long time for nothing May 19, 2016 at 18:11
  • Fun stuff this :-) can you see why it couldn't work? May 19, 2016 at 18:19
  • 1
    Hmm I might... If I'm right, cat reads the file line by line. If you add a line at the end of the file, then read a line, then write it, then read it.... Infinite recurtion May 19, 2016 at 18:25
  • Yes. Except it reads in blocks rather than lines you're spot on. (And because it reads in blocks your tiny example could have quite possibly worked; I'm off to try it...) May 19, 2016 at 19:50
0

You might try catting the file, then using sed to do an append. So something like:

cat in.txt
ip
10.22.1.34
10.22.1.35

d=1
if [ ${d} -eq 1 ]; then
    cat in.txt | while read LINE; do sed -i '$a\'"${LINE}" in.txt; done
fi

cat in.txt
ip
10.22.1.34
10.22.1.35
ip
10.22.1.34
10.22.1.35
1
  • @roaima - thank you for editing my response.
    – rsingh
    May 19, 2016 at 21:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .