Reputation: 3
I'd like to grep a string in a file and combine all the results in one line with command seperated.
grep 1000 /tmp/userfile
Output of the grep, sometimes the output is 2 liner or more.
user12:x:1000:user12,user100,user200,user300,user400,user500 user13:x:1000:user13,user600,user700,user800,user900,user1000 user14:x:1000:user14,user2600,user2700,user2800,user2900,user21000
what I want to achieve is to remove user12:x:1000:user12, user13:x:1000:user13 and user14:x:1000:user14 then combined everyone with command seperated like the one below.
user100,user200,user300,user400,user500,user600,user700,user800,user900,user1000,user2600,user2700,user2800,user2900,user21000
Hope someone can help me with this. thanks.
Upvotes: 0
Views: 2951
Reputation: 1027
grep 1000 /tmp/userfile | cut -d, -f2- | tr '\n' ',' | sed 's/,$//'
alternatively (in fact, better), as devnull suggests:
grep 1000 /tmp/userfile | cut -d, -f2- | paste -sd,
Upvotes: 3
Reputation: 51583
awk '/1000/ {string+=$0 ","} end {print substr(string,1,length(string)}' INPUTFILE
Might do it.
On every line with the matching 1000
append the line to the string with an added comma. Finally print without the last comma.
It will fail if there is no matching line!
Upvotes: 0