简体   繁体   中英

Convert file to csv from bash with sed

I have a file with a few lines like this:

-host hostname.domain.com -os "gpl x86_64 linux-5.3.18-24.52-default" -core A.10.20 -corepatch A.10.20 -ts_core A.10.20 -ts_corepatch A.10.20 -da A.10.20 -dapatch A.10.20

I would like to convert it in the shell to a file with tabs with just the first 2 fields and skip everything else:

hostname.domain.com     gpl x86_64 linux-5.3.18-24.52-default

Maybe with sed? I suck with these commands.

You can make it work with cut/awk. Here is example with cut:

[user@host~]$ echo '-host hostname.domain.com -os "gpl x86_64 linux-5.3.18-24.52-default" -core A.10.20 -corepatch A.10.20 -ts_core A.10.20 -ts_corepatch A.10.20 -da A.10.20 -dapatch A.10.20' | cut -d " "  -f2,4,5,6
hostname.domain.com "gpl x86_64 linux-5.3.18-24.52-default"

cut -d " " will use " " as delimeter and print fields in -f flag.

And to remove ", you can use tr.

tr -d "\""
$ cat your_file | awk '{ printf "%s\t%s\n", $1, $2 }'

Awk might do it: https://www.gnu.org/software/gawk/manual/html_node/Printf-Examples.html

Awk is super versatile with this kind of thing, particularly because it can leverage the amazing printf .

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