如何在linux中获取文件的最后一行前2个字符

Rat*_*thi 2 linux bash shell awk sed

我有包含以下格式的文件,由另一个系统生成

 12;453453;TBS;OPPS;
 12;453454;TGS;OPPS;
 12;453455;TGS;OPPS;
 12;453456;TGS;OPPS;
 20;787899;THS;CLST;
 33;786789;
Run Code Online (Sandbox Code Playgroud)

我必须检查最后一行包含 33 ,然后必须继续将文件复制到其他位置。否则丢弃该文件。

目前我正在做如下

tail -1 abc.txt >> c.txt
awk '{print substr($0,0,2)}' c.txt
Run Code Online (Sandbox Code Playgroud)

那么如果o/p被保存到另一个变量并复制。 任何人都可以建议任何其他简单的方法。

谢谢你!

右/

All*_*lan 5

假设您有以下输入文件:

$ cat file
a
b
c
d
e
agc
Run Code Online (Sandbox Code Playgroud)

然后您可以运行以下命令(grep, awk, sed, cut)来获取最后一行的前 2 个字符:

AWK

$ awk 'END{print substr($0,0,2)}' file
ag
Run Code Online (Sandbox Code Playgroud)

SED

$ sed -n '$s/^\(..\).*/\1/p' file                             
ag
Run Code Online (Sandbox Code Playgroud)

GREP

$ tail -1 file | grep -oE '^..' 
ag
Run Code Online (Sandbox Code Playgroud)

$ tail -1 file | cut -c '1-2' 
ag
Run Code Online (Sandbox Code Playgroud)

BASH 子字符串

line=$(tail -1 file); echo ${line:0:2}
Run Code Online (Sandbox Code Playgroud)

所有这些命令都会执行您要查找的操作,该awk命令只会在文件的最后一行执行操作,因此您不再需要tail,该命令将提取文件的最后一行并将其存储在其模式缓冲区中,然后将不是前 2 个字符的所有内容替换为空,然后打印模式缓冲区(最后一行的第 2 个字符),另一个解决方案是仅到tail文件的最后一行并使用 提取前 2 个字符grep,通过管道这两个命令,您还可以一步完成它,而无需使用中间变量、文件。

现在,如果您想将所有内容放入一个脚本中,则变为:

$ more file check_2chars.sh 
::::::::::::::
file
::::::::::::::
a
b
c
d
e
33abc
::::::::::::::
check_2chars.sh
::::::::::::::
#!/bin/bash
s1=$(tail -1 file | cut -c 1-2) #you can use other commands from this post
s2=33

if [ "$s1" == "$s2" ] 
then
   echo "match" #implement the copy/discard logic
fi
Run Code Online (Sandbox Code Playgroud)

执行:

$ ./check_2chars.sh
match
Run Code Online (Sandbox Code Playgroud)

我会让你实现复制/丢弃逻辑

证明:

在此输入图像描述