Find the answer to your Linux question:
Results 1 to 2 of 2
Hello, I have two files; file1; 1/ 2/ 3/ 4/ file2; a b c d I want to use sed to append the contents of file2 to file1 line-by-line, so ...
  1. #1
    Just Joined!
    Join Date
    Aug 2010
    Posts
    5

    add lines from a file to the end of another file with sed

    Hello,

    I have two files;

    file1;
    1/
    2/
    3/
    4/

    file2;
    a
    b
    c
    d

    I want to use sed to append the contents of file2 to file1 line-by-line, so that the end result looks like this;

    1/a
    2/b
    3/c
    4/d

    how do I do this? I've tried sed '$r file2' file1, but that just appends it at the end of the file, rather than line-by-line.

  2. #2
    Linux Enthusiast meton_magis's Avatar
    Join Date
    Oct 2006
    Location
    arizona
    Posts
    665
    I was interested in your problem, so I created a script to do what you're looking to do.

    Code:
    file1Count=`wc -l $1 | awk '{print $1}'`
    file2Count=`wc -l $2 | awk '{print $1}'`
    
    if (($file1Count >= $file2Count))
      then
        lineCount=${file1Count}
      else
        lineCount=${file2Count}
    fi
    
    i=1
    done
    while ((${i} <= ${lineCount}))
    do
      echo `sed -n ${i}p $1; sed -n ${i}p $2` | sed 's/\n//'
      let i++
    done
    create a file named "something.sh" dump this code in there, and run `chmod 755 something.sh` then run `./something.sh file1 file2`

    it will do what you want. I'm sure there are much better ways to get it done, but I'm lazy, and this works.

    If you've done any programming before you should be able to read it without issues, but the key thing is the
    echo `sed -n ${i}p file1; sed -n ${i}p file2` | sed 's/\n //g'
    line. all it does is print 1 line from each file, and remove the newline that is added automatically. Then loop, and do it again, until every line in the 2 files are run through.

    this should work, though you really should read Advanced Bash-Scripting Guide if you're going to be doing any real amount scripting.
    New to the internet, technical forums, or the hacker / open source community??
    Read this to learn good posting habits http://www.catb.org/~esr/faqs/smart-questions.html

    RHCE for RHEL version 5
    RHCT for RHEL version 4

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...