Wednesday, October 26, 2022

[SOLVED] How to use awk or sed to combine match content from two files

Issue

I have two file, file1 and file2
I need to search file2 with each line of file1, and put them together in another form once match
my progress:

awk 'FNR==NR{ids[$0]=$0;next}{for(id in ids){if($0 ~ "\\y"id"\\y"){print "- name:"id; print "  version: " ; print}}}' file1 file2

file1:

attr-2.4.48
bzip2-1.0.8
curl-7.71.1
dnsmasq-2.86
dropbear-2022.82
elfutils-0.179
ethtool-5.4

file2:

  url: https://sourceforge.net/projects/lzmautils/files/xz-5.2.5.tar.gz/download
  url: http://download.savannah.nongnu.org/releases/attr/attr-2.4.48.tar.gz
  url: https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz
  url: https://curl.se/download/curl-7.71.1.tar.bz2
  url: https://sourceware.org/elfutils/ftp/0.179/elfutils-0.179.tar.bz2
  url: https://git.kernel.org/pub/scm/network/ethtool/ethtool.git/snapshot/ethtool-5.4.tar.gz

output

- name: attr
  version: 2.4.48
  url: http://download.savannah.nongnu.org/releases/attr/attr-2.4.48.tar.gz
- name: bzip2
  version: 1.0.8
  url: https://sourceware.org/pub/bzip2/bzip2-1.0.8.tar.gz
- name: curl
  version: 7.71.1
  url: https://curl.se/download/curl-7.71.1.tar.bz2
- name: dnsmasq
  version: 2.86
  url:
- name: dropbear
  version: 2022.82
  url:
- name: elfutils
  version: 0.179
  url: https://sourceware.org/elfutils/ftp/0.179/elfutils-0.179.tar.bz2
- name: ethtool
  version: 5.4
  url: https://git.kernel.org/pub/scm/network/ethtool/ethtool.git/snapshot/ethtool-5.4.tar.gz

Solution

sed 'h;s/-/\n version: /;s/^/- name: /p;g;s/-.*//;s/^/grep /;s/$/ file2/e' file1 | sed 's/^$/ url:/'

  • use sed to h hold the original fine from file1
  • s/-/\n version: /;s/^/- name:/p print version/name
  • g get the original line again
  • s/^/grep /;s/$/ file2/e used s///e to create a grep command and execute it
  • | sed 's/^$/ url:/' clean up empty lines

Basically looping over the lines of file1 with sed, calling grep with s///e.



Answered By - stevesliva
Answer Checked By - Senaida (WPSolving Volunteer)