简体   繁体   中英

unix: Using grep or awk - need to find occurrence of a letter on specific field print the line

I have several fixed files and need to quickly scan them for occurrence of letter L on field 159 and print. Example:

123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657BA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
12345        3253657LA00000000MMMKSNS

I tried grep -E '^.{21} L' but doesn't find for a 180 fixed length grep -E '^.{159} L'

With awk you can print the substring. See nim's answer for syntax.

while read line; \
  do echo "$line" | awk '{print substr($0,21,1)}'| \
  grep -q "L"; [ $? -eq 0 ] && \
  echo "$line"; \
  done < "${file}"

Output:

123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
12345        3253657LA00000000MMMKSNS

You were very close,

echo "123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657BA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
12345        3253657LA00000000MMMKSNS" | grep -E '^.{20}L'

output

123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
123456ABCDEF23253657LA00000000MMMKSNS
12345        3253657LA00000000MMMKSNS

Note that having a space between {20} L throws off the position, AND that as your L is in Position 21, you skip 20 chars.

IHTH

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