首页 > 解决方案 > Split export format in bash

问题描述

Given a file with the following syntax:

export 'my_var1=value1' 'my_var2=value2' 'my_var3=value3'
export 'my_var3=value3' 'my_var4=value4'

Are there any way to split it in bash order to get the variables names?

my_var1
my_var2 
my_var3

I thought first spliting by line and then by space. But "values" can contain spaces. I think the key is in the quotes.

Thanks.

标签: bash

解决方案


awk 可以很好地解决这个问题,并且相当容易阅读。

awk -F "export '|' '|'$" '{for(i=1;i<NF;i++){if(split($i,arr,"=")==2)print arr[1]}}' file

解释:

-F "export '|' '|'$"- 三种模式(export ', ' ', '$)中的任何一种都用于分隔每一行。

if(split($i,arr,"=")==2)print arr[1]- 对于每个标记,用 分隔=,如果有两个标记,则打印第一个。

编辑:正如评论中指出的那样,当值可以有超过 2 个标记时,需要制作 '= 分隔符和处理:

awk -F "export '|' '|'$" '{for(i=1;i<NF;i++){if(split($i,arr,"\x27=")!=0)print arr[1]}}' file

推荐阅读