从左侧提取文件字符串,但从右侧开始遵循第二个分隔符



以下是完整的文件名。

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

使用允许操作NFGNU 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.

最新更新