下面是完整的文件名。
qwertyuiop.abcdefgh.1234567890.txt
qwertyuiop.1234567890.txt尝试使用
awk -F'.' '{print $1}'如何使用awk命令提取以下输出。
qwertyuiop.abcdefgh
qwertyuiop编辑
我在一个目录中有一个文件列表,我试图将时间、大小、所有者、文件名提取到单独的变量中。
用于文件名。
NAME=$(ls -lrt /tmp/qwertyuiop.1234567890.txt | awk -F'/' '{print $3}' | awk -F'.' '{print $1}')
$ echo $NAME
qwertyuiop
$
NAME=$(ls -lrt /tmp/qwertyuiop.abcdefgh.1234567890.txt | awk -F'/' '{print $3}' | awk -F'.' '{print $1}')
$ echo $NAME
qwertyuiop
$ 期望的
qwertyuiop.abcdefgh发布于 2018-09-25 14:30:25
编辑:从Sundeep先生的解决方案中获得了灵感,并在本文中添加了以下内容。
awk 'BEGIN{FS=OFS="."} {$(NF-1)=$NF="";sub(/\.+$/,"")} 1' Input_file你能不能试着跟上。
awk -F'.' '{for(i=(NF-1);i<=NF;i++){$i=""};sub(/\.+$/,"")} 1' OFS="." Input_file或
awk 'BEGIN{FS=OFS="."} {for(i=(NF-1);i<=NF;i++){$i=""};sub(/\.+$/,"")} 1' Input_file解释:在这里也添加了上面代码的解释。
awk '
BEGIN{ ##Mentioning BEGIN section of awk program here.
FS=OFS="." ##Setting FS and OFS variables for awk to DOT here as per OPs sample Input_file.
} ##Closing BEGIN section here.
{
for(i=(NF-1);i<=NF;i++){ ##Starting for loop from i value from (NF-1) to NF for all lines.
$i="" ##Setting value if respective field to NULL.
} ##Closing for loop block here.
sub(/\.+$/,"") ##Substituting all DOTs till end of line with NULL in current line.
}
1 ##Mentioning 1 here to print edited/non-edited current line here.
' Input_file ##Mentioning Input_file name here.发布于 2018-09-25 14:35:11
使用允许操作NF的GNU awk和其他版本
$ awk -F. -v OFS=. '{NF-=2} 1' ip.txt
qwertyuiop.abcdefgh
qwertyuiopNF-=2将有效地删除最后两个fields1是用于打印$0与perl的概念类似,如果行中的字段数小于3,则打印空行
$ perl -F'\.' -lane 'print join ".", @F[0..$#F-2]' ip.txt
qwertyuiop.abcdefgh
qwertyuiop使用sed,如果字段数小于3,则可以保留行
$ sed 's/\.[^.]*\.[^.]*$//' ip.txt
qwertyuiop.abcdefgh
qwertyuiophttps://stackoverflow.com/questions/52491802
复制相似问题