我有一个产生这种线条的文件。我想编辑这些行并将其放入passageiros.txt
a82411:x:1015:1006:Adriana Morais,,,:/home/a82411:/bin/bash
a60395:x:1016:1006:Afonso Pichel,,,:/home/a60395:/bin/bash
a82420:x:1017:1006:Afonso Alves,,,:/home/a82420:/bin/bash
a69225:x:1018:1006:Afonso Alves,,,:/home/a69225:/bin/bash
a82824:x:1019:1006:Afonso Carreira,,,:/home/a82824:/bin/bash
a83112:x:1020:1006:Aladje Sanha,,,:/home/a83112:/bin/bash
a82652:x:1022:1006:Alexandre Ferreira,,,:/home/a82652:/bin/bash
a83063:x:1023:1006:Alexandre Feijo,,,:/home/a83063:/bin/bash
a82540:x:1024:1006:Ana Santana,,,:/home/a82540:/bin/bash
使用以下代码,我可以得到如下内容:
cat /etc/passwd |grep "^a[0-9]" | cut -d ":" -f1,5 | sed "s/a//" | sed "s/,//g" > passageiros.txt
sed -e "s/$/:::a/" -i passageiros.txt
82411:Adriana Morais:::a
60395:Afonso Pichel:::a
82420:Afonso Alves:::a
69225:Afonso Alves:::a
82824:Afonso Carreira:::a
83112:Aladje Sanha:::a
82652:Alexandre Ferreira:::a
83063:Alexandre Feijo:::a
82540:Ana Santana:::a
所以我的目标是创建这样的东西:
82411:Adriana Morais:::a82411@
60395:Afonso Pichel:::a60395@
82420:Afonso Alves:::a82420@
69225:Afonso Alves:::a69225@
82824:Afonso Carreira:::a82824@
83112:Aladje Sanha:::a83112@
82652:Alexandre Ferreira:::a82652@
83063:Alexandre Feijo:::a83063@
82540:Ana Santana:::a82540@
我该怎么做?
答案 0 :(得分:3)
请您尝试以下。
awk -F'[:,]' '{val=$1;sub(/[a-z]+/,"",$1);print $1,$5,_,_,val"@"}' OFS=":" Input_file
说明: 也为上述代码添加了说明。
awk -F'[:,]' ' ##Starting awk script here and making field seprator as colon and comma here.
{ ##Starting main block here for awk.
val=$1 ##Creating a variable val whose value is first field.
sub(/[a-z]+/,"",$1) ##Using sub for substituting any kinf of alphabets small a to z in first field with NULL here.
print $1,$5,_,_,val"@" ##Printing 1st, 5th field and printing 2 NULL variables and printing variable val with @.
} ##Closing block for awk here.
' OFS=":" Input_file ##Mentioning OFS value as colon here and mentioning Input_file name here.
编辑: 也在此处添加@Aserre的解决方案。
awk -F'[:,]' '{print substr($1, 2),$5,_,_,$1"@"}' OFS=":" Input_file
答案 1 :(得分:1)
您可以使用以下awk
:
awk 'BEGIN {FS=OFS=":"} {sub(/^a/, "", $1); gsub(/,/, "", $5); print $1, $5, _, _, "a" $1 "@"}' file > passageiros.txt
请参见here
详细信息
BEGIN {FS=OFS=":"}
将输入和输出字段分隔符设置为:
sub(/^a/, "", $1)
从字段1中删除第一个a
gsub(/,/, "", $5)
从字段5中删除所有,
print $1, $5, _, _, "a" $1 "@"
仅将必要的字段输出到输出中。答案 2 :(得分:0)
您只能使用一个sed:
grep '^a' file | cut -d: -f1,5 | sed 's/a\([^:]*\)\(.*\)/\1\2:::a\1@/;s/,,,//'