以下是完整的文件名。
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
使用允许操作NF
的GNU awk
和其他版本
$ awk -F. -v OFS=. '{NF-=2} 1' ip.txt
qwertyuiop.abcdefgh
qwertyuiop
NF-=2
将有效地删除最后两个字段1
是打印$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
qwertyuiop
编辑: 从Sundeep sir的解决方案中汲取灵感,并在此组合中添加以下内容。
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.