我有以下字串:
text/:some_random_text:text_i_w4nt_to:k33p.until_th3_end_1
text/:some_random_text:text_i_w4nt_to::k33p.until_th3_end_1
使用正則運算式,我想提取:
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
我嘗試使用 regex101.com 使用以下運算式:([^:] )(?::[^:] ){1}$
它有效(僅適用于第一個字串)
但是如果我在 bash 中嘗試,它不會
echo "text/:some_random_text:text_i_w4nt_to::k33p.until_th3_end_1" | sed -n "/([^:] )(?::[^:] ){1}$/p"
uj5u.com熱心網友回復:
cut沒有任何正則運算式會容易得多:
cut -d: -f3- file
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
uj5u.com熱心網友回復:
(?:不支持非捕獲組sed,您必須轉義\( \) \{ \}和\
您可以從字串的開頭重復出現 2 次,:并將其替換為空字串。
sed 's/^\([^:]\ :\)\{2\}//' file
或sed -E用于擴展正則運算式:
sed -E 's/^([^:] :){2}//' file
輸出
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
uj5u.com熱心網友回復:
使用sed
$ sed s'|\([^:]*:\)\{2\}\(.*\)$|\2|' input_file
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
或者
$ sed s'|\([^:]*:\)\{2\}||' input_file
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
uj5u.com熱心網友回復:
沒有理由將sed其他外部程式拖入其中;只需使用 bash 內置的正則運算式匹配:
#!/usr/bin/env bash
strings=(text/:some_random_text:text_i_w4nt_to:k33p.until_th3_end_1
text/:some_random_text:text_i_w4nt_to::k33p.until_th3_end_1)
for s in "${strings[@]}"; do
[[ $s =~ ^([^:]*:){2}(.*) ]] && printf "%s\n" "${BASH_REMATCH[2]}"
done
哎呀,你不需要 bash 中的正則運算式:
printf "%s\n" "${s#*:*:}"
uj5u.com熱心網友回復:
awk
string='ext/:some_random_text:text_i_w4nt_to:k33p.until_th3_end_1
text/:some_random_text:text_i_w4nt_to::k33p.until_th3_end_1'
awk -vFS=: -vOFS=: '{$1=$2="";gsub(/^::/,"")}1' <<<"$string"
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
uj5u.com熱心網友回復:
絕對不需要使用任何需要的東西regex-backreferences,因為正則運算式錨定就在行頭:
mawk NF OFS= FS='^[^:]*:[^:]*:'
text_i_w4nt_to:k33p.until_th3_end_1
text_i_w4nt_to::k33p.until_th3_end_1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483127.html
