Sam*_*ley 5 mysql sql csv sed converters
世界另一端的一位同事以文本格式向我发送了 MySQL CLI 客户端查询的一些输出。她无法为我将其转换为 CSV,也无法使用INTO OUTFILE输出标志直接输出为 CSV。如何将其转换为 CSV 格式?它看起来像这样:
+-------------+------------------+------------------------------------------+-------------+
| pet_id      | pet_identity_id  | identity_value                           | pet_species |
+-------------+------------------+------------------------------------------+-------------+
|       77626 |          3140819 | dominic_dog@example.com                  | dog         |
|       77625 |          3140818 | missy_miauw@example.com                  | cat         |
|       77622 |          3140815 | shelly@example.com                       | aardvark    |
|       77583 |          3140776 | monster_moo@example.com                  | cow         |
+-------------+------------------+------------------------------------------+-------------+
4 rows in set (0.01 sec)
我希望它看起来像这样的 CSV 格式(管道或逗号分隔):
"pet_id"|"pet_identity_id"|"identity_value"|"pet_species"
77626|3140819|"dominic_dog@example.com"|"dog"
77625|3140818|"missy_miauw@example.com"|"cat"
77622|3140815|"shelly@example.com"|"aardvark"
77583|3140776|"monster_moo@example.com"|"cow"
我发现了各种问题,可以让您使用符号在 CLI 客户端中执行此操作INTO OUTFILE,但没有什么可以仅将某人发送给您的查询示例转换为您在 MySQL 客户端屏幕上看到的形式。
这是一个使用 sed 的小 shell 脚本,它可以做到这一点:
#!/bin/bash
# A script to convert MySQL CLI output to CSV format
# cat the file and pipe to the next step
cat $1 | \
# grep only the lines with '|' in them
grep "\|" | \
# Remove the lines which begin with '+'
sed -e '/^+/d' | \
# Remove the whitespace around the '|' characters
sed -e 's/[[:space:]]*|[[:space:]]*/|/g' | \
# Put a double quote before every '|' character
sed -e 's/|\(.\{1\}\)/\"&/g' | \
# Put a double quote after every '|' character
sed -e 's/\(.\{1\}\)|/&\"/g' | \
# Remove the extra '"|' from the beginning of each line
sed -e 's/^\"|//g' | \
# Remove the extra '"' from the end of each line
sed -e 's/\"$//g' | \
# Remove the '|' from the end of each line
sed -e 's/|$/\"/g' | \
# Remove the quotes from any purely numeric fields
sed -e 's/"\([[:digit:]]*\)"/\1/g'
只需将文件保存为例如convert-mysql.sh,然后将MySQL输出复制并粘贴到文本文件mysql-output.txt并运行例如:
$ bash ./convert-mysql.sh mysql-output.txt
这会给你这个输出:
"pet_id"|"pet_identity_id"|"identity_value"|"pet_species"
77626|3140819|"dominic_dog@example.com"|"dog"
77625|3140818|"missy_miauw@example.com"|"cat"
77622|3140815|"shelly@example.com"|"aardvark"
77583|3140776|"monster_moo@example.com"|"cow"
这在 Mac 上有效,尽管 sed 在各种 Linux 版本上可能略有不同,例如[[:digit:]]*在我上面的 shell 脚本中是[[:digit:]]+我发现的一些示例。
| 归档时间: | 
 | 
| 查看次数: | 1117 次 | 
| 最近记录: |