我想从关键字“/”和“NET”之间的文件中提取用户名,如下所示。我该如何使用awk
,sed
或 之类的程序来做到这一点cut
?
从:
audit: command=true rsa1/[email protected] running
audit: command=true user2/[email protected] executing
到:
audit: command=true rsa1 running
audit: command=true user2 executing
答案1
使用sed
:
< inputfile sed 's/\/.*NET//' > outputfile
sed
就地使用:
sed -i.bak 's/\/.*NET//' inputfile
命令 #1 故障:
< inputfile
: 将内容重定向inputfile
到sed
'sstdin
> outputfile
sed
:将 的内容重定向stdout
到outputfile
命令#2 细分:
-i.bak
:强制sed
创建备份文件并就地inputfile.bak
编辑inputfile
inputfile
:强制sed
读取输入inputfile
正则表达式分解:
s
:断言执行替换/
:开始搜索模式\/
: 匹配一个/
字符.*NET
NET
:匹配字符串末尾之前的任意数量的任意字符/
:停止搜索模式/开始替换模式/
:停止替换模式
示例输出:
~/tmp$ cat inputfile
audit: command=true rsa1/[email protected] running
audit: command=true user2/[email protected] executing
~/tmp$ < inputfile sed 's/\/.*NET//' > outputfile
~/tmp$ cat outputfile
audit: command=true rsa1 running
audit: command=true user2 executing
~/tmp$ sed -i.bak 's/\/.*NET//' inputfile
~/tmp$ cat inputfile.bak
audit: command=true rsa1/[email protected] running
audit: command=true user2/[email protected] executing
~/tmp$ cat inputfile
audit: command=true rsa1 running
audit: command=true user2 executing
~/tmp$
答案2
您也可以尝试awk
:
awk '{ split($3, a, "/"); $3 = a[1]; } 1' file