简体   繁体   中英

How to use bash to print all items in a list, including those delimited by commas?

Okay, so I have file.txt, which has two tab-delimited lists:

A   sheep,cow
B   pig
C   horse
D   goat,duck,llama

I would like to print all of the items in the second list in a new file, file2.txt, even the items delimited by commas:

sheep
cow
pig
horse
goat
duck
llama

I tried doing this:

cat file.txt | awk 'NR>1 {for (i=2; i<=NF; i++) if ($i !=",") print $i}' | sort -d | uniq > file2.txt

...but it just doesn't register that items delimited by , are different items.

Any ideas? Should I remove the first column, make everything after a comma appear in a new column, and then print all the entries in all the columns?

I'd take the easy way out:

$ cut -f 2 file.txt | tr ',' '\n'
sheep
cow
pig
horse
goat
duck
llama

It gets the second column, and replaces commas with linefeeds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM