从左侧提取文件字符串,但从右侧提取第二个定界符

时间:2018-09-25 06:22:37

标签: unix awk

下面是完整的文件名。

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

2 个答案:

答案 0 :(得分:0)

编辑: :从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

OR

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.

答案 1 :(得分:0)

使用GNU awk和其他允许操作NF的版本

$ awk -F. -v OFS=. '{NF-=2} 1' ip.txt
qwertyuiop.abcdefgh
qwertyuiop
  • NF-=2将有效删除最后两个字段
  • 1是awk习语,用于打印$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