bash 动态更改 AWK 字段分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39231787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:07:25  来源:igfitidea点击:

Change AWK field separator on the fly

linuxbashawk

提问by Ryan R

I'd like to use AWK to take the following spread sheet where the first name and last name are in one column:

我想使用 AWK 来获取以下电子表格,其中名字和姓氏位于一列中:

Peter Griffin, 31 Spooner St, Quahog
Homer Simpson, 732 Evergreen Terr, Springfield
Fred Flintstone, 301 Cobblestone Way, Bedrock

and output to a new spreadsheet where the first name and last name have their own columns:

并输出到一个新的电子表格,其中名字和姓氏有自己的列:

Peter, Griffin, 31 Spooner St, Quahog
Homer, Simpson, 732 Evergreen Terr, Springfield
Fred, Flintstone, 301 Cobblestone Way, Bedrock

I've tried changing field separators on the fly doing something like:

我尝试过动态更改字段分隔符,例如:

awk '{print  "," } {FS=","} {print } {FS=" "}' spreadsheet.csv

but it doesn't seem to work that way, and I get a jumbled mess. Is this possible using AWK?

但它似乎并没有那样工作,而且我弄得一团糟。这可以使用 AWK 吗?

采纳答案by fedorqui 'SO stop harming'

Just add a comma whenever a space is found in the first ,-based field:

只要在第一个,-based 字段中找到空格,就添加一个逗号:

awk 'BEGIN {FS=OFS=","} {sub(/ /, ", ", )}1' file
#                             ^    ^^
#               find a space...    ... replace it with , plus space

With your file:

使用您的文件:

$ awk 'BEGIN {FS=OFS=","} {sub(/ /, ", ", )}1' file
Peter, Griffin, 31 Spooner St, Quahog
Homer, Simpson, 732 Evergreen Terr, Springfield
Fred, Flintstone, 301 Cobblestone Way, Bedrock

This uses the function sub()to perform the replacement in the first field.

这使用函数sub()在第一个字段中执行替换。

回答by John1024

Replace the first space with a comma-space:

用逗号空格替换第一个空格:

$ sed 's/ /, /' file.csv
Peter, Griffin, 31 Spooner St, Quahog
Homer, Simpson, 732 Evergreen Terr, Springfield
Fred, Flintstone, 301 Cobblestone Way, Bedrock

Here, s/ /, /is a substitute command. It replaces the first found with ,.

这里,s/ /, /是一个替代命令。它将第一个找到的替换为,

To change the file in place, use the -ioption:

要就地更改文件,请使用以下-i选项:

sed -i.bak 's/ /, /' file.csv

回答by Chem-man17

You can use multiple separators as-

您可以使用多个分隔符作为-

awk -F '[ ,]' '{print  ", "  ", "   " "  " "  ", "  " " }' file

Output-

输出-

Peter, Griffin,  31 Spooner St,  Quahog
Homer, Simpson,  732 Evergreen Terr,  Springfield
Fred, Flintstone,  301 Cobblestone Way,  Bedrock

You have to keep a track of the 'columns' that get defined though.

您必须跟踪已定义的“列”。

回答by Claes Wikner

Another possibility.

另一种可能性。

awk '{=","}1' file

Peter, Griffin, 31 Spooner St, Quahog
Homer, Simpson, 732 Evergreen Terr, Springfield
Fred, Flintstone, 301 Cobblestone Way, Bedrock