I have the file1 with the following content
{"name":"clio5", "value":"13"}
{"name":"citroen_c4", "value":"23"}
{"name":"citroen_c3", "value":"12"}
{"name":"golf4", "value":"16"}
{"name":"golf3", "value":"8"}
And I have the file2 with the following content
{"name":"clio5", "value":"14"}
{"name":"citroen_c4", "value":"25"}
{"name":"golf4", "value":"18"}
I want to execute a shell command in order to display the content of the file1 and the file2. if a name
exist in both file1 and file2 so I want to display only the related line of the file2.
So the output should look like this:
$command taking account file1 file2
{"name":"clio5", "value":"14"}
{"name":"citroen_c4", "value":"25"}
{"name":"citroen_c3", "value":"12"}
{"name":"golf4", "value":"18"}
{"name":"golf3", "value":"8"}
The command should not edit file1 neither file2
Edit
The file1 and file2 have exactelly the same content format:
{"name":"any", "value":"xx"}
The command should be as simple as possible
The command could contains grep
, sed
, awk
The input looks like JSON. Using a proper tool, the JSON library for Perl:
It reads the two files, overwriting the values when reading the second one. For me, the output is not exactly what you expected:
As JSON goes, it is equivalent to your expected output, so if you always use the appropriate libraries, you will not notice the difference. If not, you have to tweak the code some more.
Or, if you really want to use sed:
The first sed invocation translates file2 into a sed script that replaces the old values in file1.
A simple change to my solution, and it seems to work:
Is the order of the output important? Otherwise you could do this, using
sort
:The change is adding
--key=1
. This means it will sort on the first column (up to first whitespace) of each line.-s
makes it not use sorting on the rest of the line, when the other sort finds two equals. The order of the files determines which file's lines will be used when there is a match.This will output the result sorted alphabetically. It looks like the input already is, in which case it should exactly what you describe (I believe). Otherwise, it would change the order of the lines (to be sorted). Not sure if that's a problem?
Here is one way with
awk
:Test:
One way is to use
join
to join both files on the name field and then useawk
to change the value. This is shown below:join
requires both files to be sorted on the join key.Alternatively, if ordering matters to you, you can use a loop to read each line and then grep the second file for the new value. This is shown below:
Output: