Is it possible to search for a string and if it exists keep that line only…the full line and not just the string? I have two comma delimited data variables. What I would like to do is loop through my $data variable and use col2 of it as a search item. Then search the $example variable and if it finds the match then prepend some data to that line only. Below this prepends the data to the correct thing but it is printing out twice because in this case there are two items. It would be nice to say don’t print anything unless it is a match and then print that whole line
#!/bin/bash
data="item,thing
item2,thing2"
example="a,lot,of,thing,in,this,csv
big,foot,lives,next,to,me,yikes"
echo "$data" | while IFS=, read -r col1 col2
do
echo "$example" | sed "s/$col1/$col2,$col1/i"
done
I have tried making col2 an array key but I wasn’t successful with it. Maybe because I’m on a Mac and from what I read it ships with an older version of Bash.
If you don’t want
sedto print unless you request it to, then you write:I’m assuming that the
isuffix is meaningful to your dialect ofsed; it isn’t standard. The-nmeans ‘do not print automatically’. The/$col1/looks for the pattern; when it is found, the commands in the braces are executed — your substitute operation and then ‘print the line’.Note that your pattern
itemwould matchnitemareif that appeared in$example.