简体   繁体   中英

Get the last two letters of each line in a file using script shell

I have a .txt file with 20 lines, and would love to get the last two letters of each line. it equals AA in every line then print Good . if not, print Bad .

line11111111111111111 AA
line22222222222222222 AA
line33333333333333333 AA
..................... 
line20202020202020202 AA

This is GOOD .

===========================

line11111111111111111 AB
line22222222222222222 AC
line33333333333333333 WD
..................... 
line20202020202020202 ZZ

This is BAD .

Did this but needs improvement : sed 's/^.*\\(.\\{2\\}\\)/\\1/'

based on your file layout

$ awk '$NF!="AA"{f=1; exit} END{print (f?"BAD":"GOOD")}' file

note that you don't have to check the rest after the first non "AA" token.

You may use a single command awk :

awk 'substr($0, length()-1) != "AA"{exit 1}' file && echo "GOOD" || echo "BAD"

substr($0, length()-1) will extract last 2 characters of every line. awk command will exit with 1 if we don't fine AA in any line.

This script shoud work with awk. The name of the txt file for me is .test you can change it with your file name.

if [ "$(awk '{ print $2 }' .test | uniq)" = "AA" ]; then 
  echo "This is GOOD"; 
else echo "This is BAD";
fi

How it works: First, awk is used to get the second column by awk '{ print $2 }' and using uniq command we are taking unique entries from each line. If all the lines are AA uniq makes it only 1 line. At last we check whether this last product is only "AA" (1 line string with 2 As) or not.

使用grep反向匹配来识别不以“ AA”结尾的行:

if egrep -q -v AA$ input.txt; then echo "bad"; else echo "good";fi

Solution with grep and wc :

if [ "`grep -v 'AA$' your-file-here | wc -l`" == "0" ] ; then echo 'GOOD' ; else echo 'BAD' ; fi

The grep command checks for all lines not ending with AA and wc counts how many lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM