1

So I have two files that look like this:

file1

userName | cpu% | command | date created

    user1 101.6 plasma-de+ Thu Aug  8 09:30:17 MDT 2019
    user2 100.0 plasma-de+ Thu Aug  8 09:30:17 MDT 2019
    user3 102.0 plasma-de+ Thu Aug  8 09:30:17 MDT 2019

file2

userName | cpu% | command | date created | date updated

    user1 101.6 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Mon Aug  5 06:35:39 MDT 2019 
    user2 100.0 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Mon Aug  5 06:35:39 MDT 2019 

file2 after command is run

userName | cpu% | command | date created | date updated

    user1 101.6 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Thu Aug  8 09:30:17 MDT 2019
    user2 100.0 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Thu Aug  8 09:30:17 MDT 2019
    user3 102.0 plasma-de+ Thu Aug  8 09:30:17 MDT 2019    Thu Aug  8 09:30:17 MDT 2019

I want to take col1 of file1 and if there is a match in col1 of file2, update the "date updated" in the last column. If there is no match, I want to append the entire line of file1 to file2 and append a "date updated" value to that line as well.

I am currently using awk 'NR==FNR{c[$1]++;next};c[$1] > 0' file2 file1 for a baseline comparison, but that wrongly prints the whole line IF there is a match and I also cannot figure out how to add another condition for updating the date column. I am also trying to do this in a shell script.

4
  • Unless I'm missing something, cp file1 file2 should do the trick. Aug 8, 2019 at 17:54
  • No I need something a bit more complex than that as I need to test for matches.
    – col
    Aug 8, 2019 at 17:56
  • 1
    Then maybe update your sample to one that demonstrates how cp file1 file2 is not enough. Aug 8, 2019 at 17:57
  • @StéphaneChazelas Okay that should make things more clear!
    – col
    Aug 8, 2019 at 18:11

1 Answer 1

0
$ cat tst.awk
BEGIN { OFS="    " }
NR==FNR {
    if (NR > 2) {
        user = $1
        file1[user] = $0
        sub(/^[[:space:]]*([^[:space:]]+[[:space:]]+){3}/,"")
        date[user] = $0
    }
    next
}
$1 in file1 {
    sub(/([[:space:]]+[^[:space:]]+){6}[[:space:]]*$/,"")
    $0 = $0 OFS date[$1]
    delete file1[$1]
}
{ print }
END {
    for (user in file1) {
        print file1[user] OFS date[user]
    }

$ awk -f tst.awk file1 file2
userName | cpu% | command | date created | date updated

    user1 101.6 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Thu Aug  8 09:30:17 MDT 2019
    user2 100.0 plasma-de+ Mon Aug  5 06:35:39 MDT 2019    Thu Aug  8 09:30:17 MDT 2019
    user3 102.0 plasma-de+ Thu Aug  8 09:30:17 MDT 2019    Thu Aug  8 09:30:17 MDT 2019

You must log in to answer this question.

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