在 bash 中解析一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/345518/
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
parsing a line in bash
提问by Alan Featherston
I have a file that has one entry per line. Each line has the following format:
我有一个文件,每行有一个条目。每行具有以下格式:
"group:permissions:users"
Permissions and users could have more than one value separated by comas like this:
权限和用户可以有多个由逗号分隔的值,如下所示:
"grp1:create,delete:yo,el,ella"
I want is to return the following:
我想要的是返回以下内容:
yo
el
ella
This is what I have so far:
这是我到目前为止:
cat file | grep grp1 -w | cut -f3 -d: | cut -d "," -f 2
This returns yo,el.ella, How can I make it return one value per line?
这将返回yo,el.ella,如何使其每行返回一个值?
回答by Jay
You can use awk, with the -F option to use : as the field separator:
您可以使用 awk,并带有 -F 选项以使用 : 作为字段分隔符:
[user@host]$ echo "grp1:create,delete:yo,el,ella" | awk -F ':' '{print }'
yo,el,ella
That will get you just the users string, separated by commas. Then you can do whatever you want with that string. If you want to literally print each user one per line, you could use tr to replace the commas with newlines:
那只会让你得到用户字符串,用逗号分隔。然后你可以用那个字符串做任何你想做的事情。如果你想每行打印每个用户一个,你可以使用 tr 用换行符替换逗号:
[user@host]$ echo "grp1:create,delete:yo,el,ella" | awk -F ':' '{print }' | tr ',' '\n'
yo
el
ella
回答by user43983
Here's one way to do it entirely in a shell script. You just need to change IFS to get it to break "words" on the right characters. Note: This will not handle escapes (e.g. ":" in some file formats) at all.
这是完全在 shell 脚本中完成的一种方法。您只需要更改 IFS 即可在正确的字符上打断“单词”。注意:这根本不会处理转义(例如,某些文件格式中的“:”)。
This is written to allow you to do:
这样做是为了让您可以:
cat file | name-of-script
The script:
剧本:
#!/bin/bash
while IFS=: read group permissions users; do
if [ "$group" = "grp1" ]; then
IFS=,
set -- $users
while [ $# -ne 0 ]; do
echo
shift
done
fi
done

