[英]Regex match and print using awk/grep/sed/bash/vim
我有一個文本文件,其中每一行具有以下結構
<six digit number>;; some text of arbitrary (non-zero) length<another six digit number>some other (possibly zero length) text
我只想從每行中提取一對六位數的數字,例如,如果某行包含
234567;; some text with any number of arbitrary characters876352some other text
輸出將是
234567;;876352
我嘗試使用awk / grep / sed / bash / vim的解決方案總數太多,無法在此處列出。 以下是其中之一
#!/bin/bash
truncate --size 0 file.out
for line in "$(cat ../allwithpins)";
do
echo $line | 'match($0, /[0123456789]{6}/, ary) {print ary[0], ary[1]}' >> file.out
# echo $line
# if [[ $line =~ [0123456789]{6} ]];
# then
# echo ${BASH_REMATCH[$1]}
# #echo ${BASH_REMATCH[$1]}
# #echo ${BASH_REMATCH[$2]}
# fi;
done
sed -r 's/^([0-9]{6};;).*([0-9]{6}).*/\1 \2/g' inputfile
234567;;876352
注意:如果您希望輸出不以;;
分隔 :
sed -r 's/^([0-9]{6}).*([0-9]{6}).*/\1 \2/g' inputfile
在這里,我們在這里捕獲(
和)
的文本組,然后使用\\1
和\\2
... \\n
引用它們。 因此可以稍后使用\\1
來表示first (``)
的內容。
使用awk
另一種解決方案
awk -F"[^0-9;]" '{print $1$(NF)}'
-F"[^0-9;]"
將字段分隔符設置為數字以外的任何其他字符;
print $1$(NF)
為每個輸入行打印由指定的分隔符分隔的第一個和最后一個字段。
NF
是字段的總數,因此$(NF)
將是最后一個字段。
例
$ echo "234567;; some text with any 123 number of arbitrary characters876352" | awk -F"[^0-9;]" '{print $1$(NF)}'
234567;;876352
編輯
如果您想在數字位數等中添加更多支票,則正則表達式比較可以為您提供幫助。
例
$ awk -F"[^0-9;]" '$1 ~ /[0-9]{6};;/ && $0 ~ /[^0-9][0-9]{6}$/{print $1$(NF)}' file
234567;;876352
234567;;876352
$ cat file
234567;; some text with any number of arbitrary characters876352
234567;; some text with any number of arbitrary characters876352iaasdfadf
234567;; some text with any number of arbitrary characters876352
234567;; some text with any number of arbitrary characters8763
234567;; some text with any number of arbitrary characters876352iaasdfadf0987654321
$1 ~ /[0-9]{6};;/
檢查第一個字段是否包含6位數字,后跟;;
$0 ~ /[^0-9][0-9]{6}$
檢查輸入行是否以6位數字結尾。 [^0-9]
檢查6位數字是否沒有其他數字的前面。
使用=~
運算符的具有內置regEx
功能的bash
解決方案(從bash 3.0
開始支持)
#!/bin/bash
while IFS= read -r line
do
[[ $line =~ ^([[:digit:]]{6}).*([[:alpha:]]+)([[:digit:]]{6})([[:alnum:]]+).*$ ]]
printf "%s %s\n" "${BASH_REMATCH[1]}" "${BASH_REMATCH[3]}"
done <file
在示例文件上運行腳本
234567;; some text with any number of arbitrary characters876352some other text
234567;; some text with any number of arbitrary characters876352abcd 124356
224967;; some text with any abpsf242432 of arbitrary characters676353abcd 2343
224967;; some text with any 222355 of arbitrary characters376353cbdw 53534e
224967;; some text with any 21462@2 of arbitrary characters476353cwsf543643
產生結果為
$ bash script.sh
234567 876352
234567 876352
224967 676353
224967 376353
224967 476353
分別是您期望的前面和后面的6位數字。
使用sed刪除數字和分號以外的所有字符:
sed 's/[^0-9;]//g' <<< "234567;; some text with any number of arbitrary characters876352some other text"
234567;;876352
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.