I have a file.csv
"ItemNo","Name","Weight"
"a001","Item a","1.1"
"a002","Item x","1.2"
"a003","Item_4","1.0"
"a004","Item b","1.1"
"a005","Itemb2","2.0"
"a006","a004","2.0"
Also I have a few itemno.csv
"a003"
"a001"
"a004"
I am looking for a command to create a list of the "Names" that are associated with the "ItemNo"...
so my output.csv should be
"Item_4"
"Item a"
"Item b"
Can somebody help?
each item.no of file.csv in the first column is unique. But there are a001, a001-b1, a001-b2 and so on.. but if you search for "a001", "a001-b1", ... everything should be unique again.
I don't need a specific tool.. every useful solution would be ok. But it would be good if only the first row is searched (assuming the Item.Name of ItemNo "a006" (column 1) is "a004" (column 2)).
I tried the grep command
grep -f itemno.csv file.csv | awk -F, '{print $2}'
But the result was only the output from the last line:
"Item b"
I tried the awk command
awk -F, 'NR==FNR{a[$1]; next} $1 in a{print $2}' itemno.csv file.csv
But the result was only the output from the last line:
"Item b"
Maybe a loop command is a better idea?
So I tried this loop
while read -r line; do
grep "${line}" file.csv | awk -F "," '{print $2}';
done < itemno.csv
But there was no output... It seems like after each line there is another \r
So I tried this command
while read line; do
grep $(printf ${line} | sed 's/\r//g') file.csv | awk -F "," '{print $2}';
done < itemno2.csv
with this itemno2.csv
"a003"
"a001"
"a002"
"a004"
And the output was:
"Item a"
"Item x"
Only with this strange loop command I manage to search for the ItemNumbers (and this command is ignoring the first and last line).
awk
orgrep
)? – AdminBee Jan 26 '23 at 13:18fromdos
. The itemno.csv file in particular needs to be converted to LF-only line-endings (otherwise the ^M in each itemno.csv line will prevent the matches from working) – cas Jan 27 '23 at 05:29sed -i.bak -e 's/\r\n/\n/' itemno.csv file.csv
. Or just tell awk to use CRLF as the record separator - i.e. addBEGIN{RS="\r\n"};
to the start of the awk script. orBEGIN{RS="\r?\n"};
to work with both dos and windows text files. – cas Jan 27 '23 at 05:31Maybe a loop command is a better idea?
- no, that'd be extremely slow and fragile, see why-is-using-a-shell-loop-to-process-text-considered-bad-practice. – Ed Morton Jan 27 '23 at 16:27