1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541
|
[![build status][ci-image]][ci-url] [![license][bsd-3-image]][bsd-3-url]
**ugrep v3.11 is now available: more features & even faster than before**
Search for anything in everything... ultra fast
*New option -Q opens a query TUI to search files as you type!*
<br>
<img src="https://www.genivia.com/images/scranim.gif" width="438" alt="">
- Ultra fast with new match algorithms and features beating grep, ripgrep, silver searcher, ack, sift, etc.
- Written in clean and efficient C++11 for advanced features and speed, thoroughly tested
- Portable (Linux, Unix, MacOS, Windows, etc), includes binaries for Windows in the [releases](https://github.com/Genivia/ugrep/releases)
- Supports all GNU/BSD grep standard options; ugrep is a faster [compatible replacement](#grep) for GNU/BSD grep
- Matches Unicode patterns by default in UTF-8, UTF-16, UTF-32 encoded files
- Matches multiple lines with `\n` and `\R` regex patterns
- Built-in help: `ugrep --help WHAT` displays options related to `WHAT` you are looking for
> 💡**ProTip** try `--help help`, `--help regex` and `--help globs`.
- User-friendly with sensible defaults and customizable [configuration files](#config) used by the `ug` command intended for interactive use that loads a .ugrep configuration file with your preferences
ug PATTERN ... ugrep --config PATTERN ...
> 💡**ProTip** `ug --save-config ...options...` saves a .ugrep config file in the working directory.
- Interactive [query TUI](#query), press F1 or CTRL-Z for help and TAB/SHIFT-TAB to navigate to dirs and files
ug -Q ug -Q -e PATTERN
> 💡**ProTip** `-Q` replaces `PATTERN` on the command line to type your patterns interactively instead. Specify `-e PATTERN` to search and edit the `PATTERN` in the TUI. For quicker search responses to keypresses, try `-Q1` (fast, 100ms delay) to `-Q5` (default 500ms delay).
- Find approximate pattern matches with [fuzzy search](#fuzzy), within the specified Levenshtein distance
ug -Z PATTERN ... ug -Z3 PATTTERN ...
> 💡**ProTip** `-Zn` matches up to `n` extra, missing or replaced characters, `-Z+n` matches up to `n` extra characters, `-Z-n` matches with up to `n` missing characters and `-Z~n` matches up to `n` replaced characters. `-Z` defaults to `-Z1`.
- Search with Google-like [Boolean query patterns](#bool) using `--bool` patterns with `AND` (or just space), `OR` (or a bar `|`), `NOT` (or a dash `-`), using quotes to match exactly, and grouping with `( )`; or with options `-e` (as an "or"), `--and`, `--andnot`, and `--not` regex patterns
ug --bool 'A B C' ... ug -e 'A' --and 'B' --and 'C' ...
ug --bool 'A|B C' ... ug -e 'A' -e 'B' --and 'C' ...
ug --bool 'A -B -C' ... ug -e 'A' --andnot 'B' --andnot 'C' ...
ug --bool 'A -(B|C)'... ug -e 'A' --andnot 'B' --andnot 'C' ...
ug --bool '"abc" "def"' ... ug -e '\Qabc\E' --and '\Qdef\E' ...
where `A`, `B` and `C` are arbitrary regex patterns (use option `-F` to search strings)
> 💡**ProTip** specify `--files --bool` to apply the Boolean query to files as a whole: a file matches if all Boolean conditions are satisfied by matching patterns file-wide. Otherwise, Boolean conditions apply to single lines by default, since grep utilities are generally line-based pattern matchers. Option `--stats` displays the query in human-readable form after the search completes.
- Fzf-like search with regex (or fixed strings with `-F`), fuzzy matching with up to 4 extra characters with `-Z+4` and words only with `-w`, using `--files --bool` for file-wide Boolean searches
ug -Q1 --files --bool -l -w -Z+4 --sort=best
> 💡**ProTip** `-l` lists the matching files in the TUI, press `TAB` then `ALT-y` to view a file, `SHIFT-TAB` and `Alt-l` to go back to view the list of matching files ordered by best match
- Search the contents of [archives](#archives) (cpio, jar, tar, pax, zip) and [compressed files](#archives) (zip, gz, Z, bz, bz2, lzma, xz, lz4, zstd)
ug -z PATTERN ... ug -z --zmax=2 PATTERN ...
> 💡**ProTip** specify `-z --zmax=2` to search compressed files and archives nested within archives, e.g. to search zip files stored in (compressed) tar files. The `--zmax` argument may range from 1 (default) to 99 for up to 99 decompression and de-archiving steps, far more than you will ever need! Larger `--zmax` slows searching.
- Search pdf, doc, docx, xls, xlxs, and more [using filters](#filter)
ug --filter='pdf:pdftotext % -' PATTERN ...
ug --filter='odt,doc,docx,rtf,xls,xlsx,ppt,pptx:soffice --headless --cat %' PATTERN ...
ug --filter='pem:openssl x509 -text,cer,crt,der:openssl x509 -text -inform der' PATTERN ...
ug --filter='latin1:iconv -f LATIN1 -t UTF-8' PATTERN ...
ug --filter='7z:7z x -so -si' PATTERN ...
> 💡**ProTip** filters are selected based on the specified list of filename extensions. Filters can be any commands (including your own scripts and executables) that take standard input to produce standard output.
- Search [binary files](#binary) and display hexdumps with binary pattern matches (Unicode text or `-U` for byte patterns)
ug --hexdump -U BYTEPATTERN ... ug --hexdump TEXTPATTERN ...
ug -X -U BYTEPATTERN ... ug -X TEXTPATTERN ...
ug -W -U BYTEPATTERN ... ug -W TEXTPATTERN ...
> 💡**ProTip** `--hexdump=4chC1` displays `4` columns of hex without a character column `c`, no hex spacing `h`, and with one extra hex line `C1` before and after a match. Option `-X` is the same as `--hexdump=2C` with `2` columns of hex and the whole matching line as `C` context in hex.
- Include files to search by [filename extensions](#magic) or exclude them with `^`
ug -O EXT PATTERN ... ug -O ^EXT PATTERN ...
- Include files to search by [file types or file "magic bytes"](#magic) or exclude them with `^`
ug -t TYPE PATTERN ... ug -t ^TYPE PATTERN ...
ug -M 'MAGIC' PATTERN ... ug -M '^MAGIC' PATTERN ...
- Include files and directories to search that match [gitignore-style globs](#globs) or exclude them with `^`
ug -g 'FILEGLOB' PATTERN ... ug -g '^FILEGLOB' PATTERN ...
ug -g 'DIRGLOB/' PATTERN ... ug -g '^DIRGLOB/' PATTERN ...
ug -g 'PATH/FILEGLOB' PATTERN ... ug -g '^PATH/FILEGLOB' PATTERN ...
ug -g 'PATH/DIRGLOB/' PATTERN ... ug -g '^PATH/DIRGLOB/' PATTERN ...
- Include [hidden files (dotfiles) and directories](#hidden) to search (omitted by default)
ug -. PATTERN ... ug -g'.*,.*/' PATTERN ...
- Exclude files specified by [.gitignore](#ignore) etc.
ug --ignore-files PATTERN ... ug --ignore-files=.ignore PATTERN ...
- Search patterns excluding [negative patterns](#not) ("match this but not that")
ug -e PATTERN -N NOTPATTERN ... ug -e '[0-9]+' -N 123 ...
- Use [predefined regex patterns](#source) to search source code, javascript, XML, JSON, HTML, PHP, markdown, etc.
ug PATTERN -f c++/zap_comments -f c++/zap_strings ...
ug PATTERN -f php/zap_html ...
ug -f js/functions ... | ug PATTERN ...
- Sort matching files by [name, best match, size, and time](#sort)
ug --sort PATTERN ... ug --sort=size PATTERN ...
ug --sort=changed PATTERN ... ug --sort=created PATTERN ...
ug -Z --sort=best PATTERN ...
- Output results in [CSV, JSON, XML](#json), and [user-specified formats](#format)
ug --csv PATTERN ... ug --json PATTERN ...
ug --xml PATTERN ... ug --format='file=%f line=%n match=%O%~' PATTERN ...
> 💡**ProTip** `ug --help format` displays help on format `%` fields.
- Search with PCRE's Perl-compatible regex patterns and display or replace [subpattern matches](#replace)
ug -P PATTERN ... ug -P --format='%1 and %2%~' 'PATTERN(SUB1)(SUB2)' ...
- Replace patterns in the output with [-P and --replace](#replace) replacement text, optionally containing `%` [formatting fields](#format), using `-y` to pass the rest of the file through:
ug --replace='TEXT' PATTERN ... ug -y --replace='TEXT' PATTERN ...
ug --replace='(%m:%o)' PATTERN ... ug -y --replace='(%m:%o)' PATTERN ...
ug -P --replace='%1' PATTERN ... ug -y -P --replace='%1' PATTERN ...
> 💡**ProTip** `ug --help format` displays help on format `%` fields to optionally use with `--replace`.
- Search files with a specific [encoding](#encoding) format such as ISO-8859-1 thru 16, CP 437, CP 850, MACROMAN, KOI8, etc.
ug --encoding=LATIN1 PATTERN ...
<a name="toc"/>
Table of contents
-----------------
- [Download and install](#install)
- [Performance comparisons](#speed)
- [Using ugrep within Vim](#vim)
- [Using ugrep within Emacs](#emacs)
- [Using ugrep to replace GNU/BSD grep](#grep)
- [Equivalence to GNU/BSD grep](#equivalence)
- [Short and quick command aliases](#aliases)
- [Notable improvements over grep](#improvements)
- [Tutorial](#tutorial)
- [Examples](#examples)
- [Advanced examples](#advanced)
- [Displaying helpful info](#help)
- [Configuration files](#config)
- [Interactive search with -Q](#query)
- [Recursively list matching files with -l, -R, -r, --depth, -g, -O, and -t](#recursion)
- [Boolean query patterns with --bool (-%), --and, --not](#bool)
- [Search this but not that with -v, -e, -N, -f, -L, -w, -x](#not)
- [Search non-Unicode files with --encoding](#encoding)
- [Matching multiple lines of text](#multiline)
- [Displaying match context with -A, -B, -C, and -y](#context)
- [Searching source code using -f, -O, and -t](#source)
- [Searching compressed files and archives with -z](#archives)
- [Find files by file signature and shebang "magic bytes" with -M, -O and -t](#magic)
- [Fuzzy search with -Z](#fuzzy)
- [Search hidden files with -.](#hidden)
- [Using filter utilities to search documents with --filter](#filter)
- [Searching and displaying binary files with -U, -W, and -X](#binary)
- [Ignore binary files with -I](#nobinary)
- [Ignoring .gitignore-specified files with --ignore-files](#ignore)
- [Using gitignore-style globs to select directories and files to search](#globs)
- [Including or excluding mounted file systems from searches](#fs)
- [Counting the number of matches with -c and -co](#count)
- [Displaying file, line, column, and byte offset info with -H, -n, -k, -b, and -T](#fields)
- [Displaying colors with --color and paging the output with --pager](#color)
- [Output matches in JSON, XML, CSV, C++](#json)
- [Customize output with --format](#format)
- [Replacing matches with -P --replace and --format using backreferences](#replace)
- [Limiting the number of matches with -1,-2...-9, -K, -m, and --max-files](#max)
- [Matching empty patterns with -Y](#empty)
- [Case-insensitive matching with -i and -j](#case)
- [Sort files by name, best match, size, and time](#sort)
- [Tips for advanced users](#tips)
- [More examples](#more)
- [Man page](#man)
- [Regex patterns](#patterns)
- [POSIX regular expression syntax](#posix-syntax)
- [POSIX and Unicode character classes](#posix-classes)
- [POSIX and Unicode character categories](#posix-categories)
- [Perl regular expression syntax](#perl-syntax)
- [Troubleshooting](#bugs)
<a name="install"/>
Download and install
--------------------
### Homebrew for MacOS (and Linux)
Install the latest **ugrep** with [Homebrew](https://brew.sh):
$ brew install ugrep
This installs the `ugrep` and `ug` commands, where `ug` is the same as `ugrep`
but also loads the configuration file .ugrep when present in the working
directory or home directory.
### Windows
Practical hints on using `ugrep.exe` and `ug.exe` for interactive use on the
Windows command line:
- when quoting patterns and arguments on the command line, do not use single
`'` quotes but use `"` instead; most Windows command utilities consider
the single `'` quotes part of the command-line argument!
- file and directory globs specified with option `-g/GLOB` may behave more
intuitively than a `GLOB` command line argument, especially when directory
recursion is enabled;
- when specifying an empty pattern `""` to match all input, this may be ignored
by some Windows command interpreters such as Powershell, in that case use
option `--match` instead;
- to match newlines in patterns, you may want to use `\R` instead of `\n` to
match any Unicode newlines, such as `\r\n` pairs and single `\r` and `\n`.
Install with [Chocolatey](https://community.chocolatey.org/packages/ugrep)
`choco install ugrep`
Or install with [Scoop](https://scoop.sh) `scoop install ugrep`
Or download the full-featured `ugrep.exe` executable as release artifact from
<https://github.com/Genivia/ugrep/releases>. Then copy `ugrep.exe` to `ug.exe`
if you also want the `ug` command intended for interactive use, which loads the
.ugrep configuration file when present in the working directory or home
directory.
Add `ugrep.exe` and `ug.exe` to your execution path: go to *Settings* and
search for "Path" in *Find a Setting*. Select *environment variables* ->
*Path* -> *New* and add the directory where you placed the `ugrep.exe` and
`ug.exe` executables.
### Alpine Linux
$ apk add ugrep ugrep-doc
Check <https://pkgs.alpinelinux.org/packages?name=ugrep> for version info.
### Arch Linux
$ pacman -S ugrep
Check <https://archlinux.org/packages/community/x86_64/ugrep> for version info.
### CentOS
First enable the [EPEL repository](https://docs.fedoraproject.org/en-US/epel/),
then you can install ugrep.
$ dnf install ugrep
Check <https://packages.fedoraproject.org/pkgs/ugrep/ugrep/> for version info.
### Debian
$ apt-get install ugrep
Check <https://packages.debian.org/ugrep> for version info. To build and try
`ugrep` locally, see "All platforms" build steps further below.
### Fedora
$ dnf install ugrep
Check <https://packages.fedoraproject.org/pkgs/ugrep/ugrep/> for version info.
### FreeBSD
$ pkg install ugrep
Check <https://www.freshports.org/textproc/ugrep> for version info.
### Haiku
$ pkgman install cmd:ugrep
Check <https://github.com/haikuports/haikuports/tree/master/app-text/ugrep> for
version info. To build and try `ugrep` locally, see "All platforms" build
steps further below.
### NetBSD
You can use the standard NetBSD package installer (pkgsrc):
<http://cdn.netbsd.org/pub/pkgsrc/current/pkgsrc/textproc/ugrep/README.html>
### RHEL
First enable the [EPEL repository](https://docs.fedoraproject.org/en-US/epel/),
then you can install ugrep.
$ dnf install ugrep
Check <https://packages.fedoraproject.org/pkgs/ugrep/ugrep/> for version info.
### Other platforms: step 1 download
Clone `ugrep` with
$ git clone https://github.com/Genivia/ugrep
Or visit <https://github.com/Genivia/ugrep/releases> to download a specific
release.
### Other platforms: step 2 consider optional dependencies
You can always add these later, when you need these features:
- Option `-P` (Perl regular expressions) requires either the PCRE2 library
(preferred) or the Boost.Regex library. If PCRE2 is not installed,
install PCRE2 with e.g. `sudo apt-get install -y libpcre2-dev` or
[download PCRE2](https://www.pcre.org) and follow the installation
instructions. Alternatively,
[download Boost.Regex](https://www.boost.org/users/download) and run
`./bootstrap.sh` and `sudo ./b2 --with-regex install`. See
[Boost: getting started](https://www.boost.org/doc/libs/1_72_0/more/getting_started/unix-variants.html).
- Option `-z` (compressed files and archives search) requires the
[zlib](https://www.zlib.net) library installed. It is installed on most
systems. If not, install it, e.g. with `sudo apt-get install -y libz-dev`.
To search `.bz` and `.bz2` files, install the
[bzip2](https://www.sourceware.org/bzip2) library, e.g. with
`sudo apt-get install -y libbz2-dev`. To search `.lzma` and `.xz` files,
install the [lzma](https://tukaani.org/xz) library, e.g. with
`sudo apt-get install -y liblzma-dev`. To search `.lz4` files, install the
[lz4](https://github.com/lz4/lz4) library, e.g. with
`sudo apt-get install -y liblz4-dev`. To search `.zst` files, install the
[zstd](http://facebook.github.io/zstd) library, e.g. with
`sudo apt-get install -y libzstd-dev`
**Note:** even if your system has command line utilities, such as `bzip2`, that
does not necessarily mean that the development libraries such as `libbz2` are
installed. The *development libraries* should be installed.
After installing one or more of these libraries, re-execute the commands to
rebuild `ugrep`:
$ cd ugrep
$ ./build.sh
**Note:** some Linux systems may not be configured to load dynamic libraries
from `/usr/local/lib`, causing a library load error when running `ugrep`. To
correct this, add `export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib"` to
your `~/.bashrc` file. Or run `sudo ldconfig /usr/local/lib`.
### Other platforms: step 3 build
Build `ugrep` on Unix-like systems with colors enabled by default:
$ cd ugrep
$ ./build.sh
This builds the `ugrep` executable in the `ugrep/src` directory with
`./configure` and `make -j`, verified with `make test`. When all tests pass,
the `ugrep` executable is copied to `ugrep/bin/ugrep` and the symlink
`ugrep/bin/ug -> ugrep/bin/ugrep` is added for the `ug` command.
Note that `ug` is the same as `ugrep` but also loads the configuration file
.ugrep when present in the working directory or home directory. This means
that you can define your default options for `ug` in .ugrep.
To build `ugrep` with specific hard defaults enabled, such as a pager:
$ cd ugrep
$ ./build.sh --enable-pager
Options to select defaults for builds include:
- `--enable-hidden` always search hidden files and directories
- `--enable-pager` always use a pager to display output on terminals
- `--enable-pretty` colorize output to terminals and add filename headings
- `--disable-auto-color` disable automatic colors, requires ugrep option `--color=auto` to show colors
- `--disable-mmap` disable memory mapped files
- `--disable-sse2` disable SSE2 and AVX optimizations
- `--disable-avx` disable AVX optimizations, but compile with SSE2 when supported
- `--disable-neon` disable ARM NEON/AArch64 optimizations
- `--with-grep-path` the default `-f` path if `GREP_PATH` is not defined
- `--with-grep-colors` the default colors if `GREP_COLORS` is not defined
- `--help` display build options
After the build completes, copy `ugrep/bin/ugrep` and `ugrep/bin/ug` to a
convenient location, for example in your `~/bin` directory. Or, if you may want
to install the `ugrep` and `ug` commands and man pages:
$ sudo make install
This also installs the pattern files with predefined patterns for option `-f`
at `/usr/local/share/ugrep/patterns/`. Option `-f` first checks the working
directory for the presence of pattern files, if not found checks environment
variable `GREP_PATH` to load the pattern files, and if not found reads the
installed predefined pattern files.
### Troubleshooting
#### Git and timestamps
Unfortunately, git clones do not preserve timestamps which means that you may
run into "WARNING: 'aclocal-1.15' is missing on your system." or that
autoheader was not found when running `make`.
To work around this problem, run:
$ autoreconf -fi
$ ./build.sh
#### Compiler warnings
GCC 8 and greater may produce warnings of the sort *"note: parameter passing
for argument ... changed in GCC 7.1"*. These warnings should be ignored.
### Dockerfile for developers
A Dockerfile is included to build `ugrep` in a Ubuntu container.
Developers may want to use sanitizers to verify the **ugrep** code when making
significant changes, for example to detect data races with the
[ThreadSanitizer](https://clang.llvm.org/docs/ThreadSanitizer.html):
$ ./build.sh CXXFLAGS='-fsanitize=thread -O1 -g'
We checked `ugrep` with the clang AddressSanitizer, MemorySanitizer,
ThreadSanitizer, and UndefinedBehaviorSanitizer. These options incur
significant runtime overhead and should not be used for the final build.
🔝 [Back to table of contents](#toc)
<a name="speed">
Performance comparisons
-----------------------
Performance comparisons should represent what users can expect the performance
to be in practice. There should not be any shenanigans to trick the system to
perform more optimally or to degrade an important aspect of the search to make
one grep tool look better than another.
**ugrep** is a no-nonsense fast search tool that utilizes a worker pool of
threads with clever lock-free job queue stealing for optimized load balancing.
A new hashing technique is used to identify possible matches to speed up
multi-pattern matches. In addition, regex matching is optimized with AVX/SSE
and ARM NEON/AArch64 instructions. Compressed files are decompressed
concurrently while searching to further increase performance. Asynchronous IO
is implemented for efficient input and output.
**ugrep** performs very well overall and particularly well when searching
compressed files and archives. This means that at its core, the search
engine's performance of ugrep excellent if not the best among grep tools
available.
### Benchmarks
The following benchmark tests span a range of practical use cases:
Test | Command | Description
---- | ---------------------------------------------------------------- | -----------------------------------------------------
T1 | `GREP -c quartz enwik8` | count "quartz" in a 100MB file (word with low frequency letters)
T2 | `GREP -c sternness enwik8` | count "sternness" in a 100MB file (word with high frequency letters)
T3 | `GREP -c 'Sherlock Holmes' en.txt` | count "Sherlock Holmes" in a huge [13GB decompressed file](http://opus.nlpl.eu/download.php?f=OpenSubtitles/v2018/mono/OpenSubtitles.raw.en.gz)
T4 | `GREP -cw -e char -e int -e long -e size_t -e void big.cpp` | count 5 short words in a 35MB C++ source code file
T5 | `GREP -Eon 'serialize_[a-zA-Z0-9_]+Type' big.cpp` | search and display C++ serialization functions in a 35MB source code file
T6 | `GREP -Fon -f words1+1000 enwik8` | search 1000 words of length 1 or longer in a 100MB Wikipedia file
T7 | `GREP -Fon -f words2+1000 enwik8` | search 1000 words of length 2 or longer in a 100MB Wikipedia file
T8 | `GREP -Fon -f words4+1000 enwik8` | search 1000 words of length 4 or longer in a 100MB Wikipedia file
T9 | `GREP -Fon -f words8+1000 enwik8` | search 1000 words of length 8 or longer in a 100MB Wikipedia file
T10 | `GREP -ro '#[[:space:]]*include[[:space:]]+"[^"]+"' -Oh,hpp,cpp` | multi-threaded recursive search of `#include "..."` in the directory tree from the Qt 5.9.2 root, restricted to `.h`, `.hpp`, and `.cpp` files
T11 | `GREP -ro '#[[:space:]]*include[[:space:]]+"[^"]+"' -Oh,hpp,cpp` | same as T10 but single-threaded
T12 | `GREP -z -Fc word word*.gz` | count `word` in 6 compressed files of 1MB to 3MB each
Note: T10 and T11 use `ugrep` option `-Oh,hpp,cpp` to restrict the search to
files with extensions `.h`, `.hpp`, and `.cpp`, which is formulated with
GNU/BSD/PCRGE grep as `--include='*.h' --include='*.hpp' --include='*.cpp'`,
with silver searcher as `-G '.*\.(h|hpp|cpp)'` requiring `--search-binary` to
search compressed files (a bug), and with ripgrep as `--glob='*.h'
--glob='*.hpp' --glob='*.cpp'`.
The corpora used in the tests are available for
[download](https://www.genivia.com/files/corpora.zip).
### Performance results
The following performance tests were conducted with a new and common MacBook
Pro using clang 12.0.0 -O2 on a 2.9 GHz Intel Core i7, 16 GB 2133 MHz LPDDR3
MacOS 10.15.7 machine with the grep tools listed in the table installed (e.g.
MacOS BSD grep 2.5.1). The best times of 30 runs is shown under minimal
machine load. When comparing tools, the same match counts were produced.
These results are reproducible on similar machines.
Results are shown in real time (wall clock time) seconds elapsed. Best times
are shown in **boldface** and *n/a* means that the running time exceeded 1
minute or the selected options are not supported (T12: option `-z`) or the
input file is too large (T3: 13GB file) resulting in an error.
GREP | T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10 | T11 | T12 |
--------------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
ugrep | **0.02** | **0.03** | **6.05** | **0.07** | **0.02** | **0.98** | **0.97** | **0.87** | **0.26** | **0.10** | **0.19** | **0.02** |
hyperscan grep | 0.09 | 0.10 | **4.35** | 0.11 | 0.04 | 7.78 | 3.39 | 1.41 | 1.17 | *n/a* | *n/a* | *n/a* |
ripgrep | 0.06 | 0.10 | 7.50 | 0.19 | 0.06 | 2.20 | 2.07 | 2.01 | 2.14 | 0.12 | 0.36 | 0.03 |
silver searcher | 0.10 | 0.11 | *n/a* | 0.16 | 0.21 | *n/a* | *n/a* | *n/a* | *n/a* | 0.45 | 0.32 | 0.09 |
GNU grep 3.3 | 0.08 | 0.15 | 11.21 | 0.18 | 0.16 | 2.70 | 2.64 | 2.42 | 2.26 | *n/a* | 0.26 | *n/a* |
PCREGREP 8.42 | 0.17 | 0.17 | *n/a* | 0.26 | 0.08 | *n/a* | *n/a* | *n/a* | *n/a* | *n/a* | 2.37 | *n/a* |
BSD grep 2.5.1 | 0.81 | 1.60 | *n/a* | 1.85 | 0.83 | *n/a* | *n/a* | *n/a* | *n/a* | *n/a* | 3.35 | 0.60 |
Note T3: [Hyperscan simplegrep](https://github.com/intel/hyperscan/tree/master/examples)
was compiled with optimizations enabled. Hyperscan results for T3 are somewhat
better than ugrep as expected because hyperscan simplegrep has one advantage
here: it does not maintain line numbers and other line-related information. By
contrast, line information should be tracked (as in ugrep) to determine if
matches are on the same line or not, as required by option `-c`. Hyperscan
simplegrep returns more matches than other greps due to its "all matches
reported" pattern matching behavior.
Note T4-T9: Hyperscan simplegrep does not support command line options. Option
`-w` was emulated using the pattern `\b(char|int|long|size_t|void)\b`. Option
`-f` was emulated as follows:
paste -d'|' -s words1+1000 > pattern.txt
/usr/bin/time ./simplegrep `cat pattern.txt` enwik8 | ./null
Note T10+T11: [silver searcher 2.2.0](https://github.com/ggreer/the_silver_searcher)
runs slower with multiple threads (T10 0.45s) than single-threaded (T11 0.32s),
which was reported as an issue to the maintainers.
Note: ugrep option `-c` does not shortcut the search by skipping over the rest
of the line after a first match, by contrast to other grep to speed up
matching. The reason is that ugrep supports multi-line matches by default,
which means that the remainder of the line should always be searched to produce
accurate results.
Output is sent to a `null` utility to eliminate terminal display overhead
(`> /dev/null` cannot be used as some greps detect it to remove all output).
The `null` utility source code:
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
int main() { char buf[65536]; while (read(0, buf, 65536) > 0) continue; }
Performance results may depend on warm/cold runs, compilers, libraries,
the OS, the CPU type, and file system latencies. However, comparable
competitive results were obtained on many other types of machines.
🔝 [Back to table of contents](#toc)
<a name="vim"/>
Using ugrep within Vim
----------------------
First, let's define the `:grep` command in Vim to search files recursively. To
do so, add the following lines to your `.vimrc` located in the root directory:
if executable('ugrep')
set grepprg=ugrep\ -RInk\ -j\ -u\ --tabs=1\ --ignore-files
set grepformat=%f:%l:%c:%m,%f+%l+%c+%m,%-G%f\\\|%l\\\|%c\\\|%m
endif
This specifies `-j` [case insensitive searches](#case) with the Vim `:grep`
command. For case sensitive searches, remove `\ -j` from `grepprg`. Multiple
matches on the same line are listed in the quickfix window separately. If this
is not desired, remove `\ -u` from `grepprg`. With this change, only the first
match on a line is shown. Option `--ignore-files` skips files specified in
`.gitignore` files, when present. To limit the depth of recursive searches to
the current directory only, append `\ -1` to `grepprg`.
You can now invoke the Vim `:grep` command in Vim to search files on a
specified `PATH` for `PATTERN` matches:
:grep PATTERN [PATH]
If you omit `PATH`, then the working directory is searched. Use `%` as `PATH`
to search only the currently opened file in Vim:
:grep PATTERN %
The `:grep` command shows the results in a
[quickfix](http://vimdoc.sourceforge.net/htmldoc/quickfix.html#:grep) window
that allows you to quickly jump to the matches found.
To open a quickfix window with the latest list of matches:
:copen
Double-click on a line in this window (or select a line and press ENTER) to
jump to the file and location in the file of the match. Enter commands `:cn`
and `:cp` to jump to the next or previous match, respectively. To update the
search results in the quickfix window, just grep them. For example, to
recursively search C++ source code marked `FIXME` in the working directory:
:grep -tc++ FIXME
To close the quickfix window:
:cclose
You can use **ugrep** options with the `:grep` command, for example to
select single- and multi-line comments in the current file:
:grep -f c++/comments %
Only the first line of a multi-line comment is shown in quickfix, to save
space. To show all lines of a multi-line match, remove `%-G` from
`grepformat`.
A popular Vim tool is [ctrlp.vim](http://kien.github.io/ctrlp.vim), which is
installed with:
$ cd ~/.vim
$ git clone https://github.com/kien/ctrlp.vim.git bundle/ctrlp.vim
CtrlP uses **ugrep** by adding the following lines to your `.vimrc`:
if executable('ugrep')
set runtimepath^=~/.vim/bundle/ctrlp.vim
let g:ctrlp_match_window='bottom,order:ttb'
let g:ctrlp_user_command='ugrep "" %s -Rl -I --ignore-files -3'
endif
where `-I` skips binary files, option `--ignore-files` skips files specified in
`.gitignore` files, when present, and option `-3` restricts searching
directories to three levels (the working directory and up to two levels below).
Start Vim then enter the command:
:helptags ~/.vim/bundle/ctrlp.vim/doc
To view the CtrlP documentation in Vim, enter the command:
:help ctrlp.txt
🔝 [Back to table of contents](#toc)
<a name="emacs"/>
Using ugrep within Emacs
------------------------
Thanks to [Manuel Uberti](https://github.com/emacs-mirror/emacs/commits?author=manuel-uberti),
you can now use **ugrep** in Emacs. To use **ugrep** instead of GNU grep
within Emacs, add the following line to your `.emacs.d/init.el` file:
(setq-default xref-search-program ‘ugrep)
This means that Emacs commands such as `project-find-regexp` that rely on
[Xref](https://www.gnu.org/software/emacs/manual/html_node/emacs/Xref.html) can
now leverage the power of **ugrep**.
Furthermore, it is possible to use `grep` in the [Emacs grep
commands](https://www.gnu.org/software/emacs/manual/html_node/emacs/Grep-Searching.html).
For instance, you can run `lgrep` with `ugrep` by customizing `grep-template`
to something like the following:
(setq-default grep-template "ugrep --color=always -0Iinr -e <R>")
If you do not have Emacs version 29 (or greater) you can download and build
Emacs from the [Emacs master branch](https://github.com/emacs-mirror/emacs),
or enable Xref integration with **ugrep** manually:
(with-eval-after-load 'xref
(push '(ugrep . "xargs -0 ugrep <C> --null -ns -e <R>")
xref-search-program-alist)
(setq-default xref-search-program 'ugrep))
🔝 [Back to table of contents](#toc)
<a name="grep"/>
Using ugrep to replace GNU/BSD grep
-----------------------------------
Out-of-the-box **ugrep** supports all standard GNU/BSD grep command-line
options and improves many of them too. For details see [notable improvements
over grep](#improvements).
If you want to stick exactly to GNU/BSD grep ASCII/LATIN1 non-UTF Unicode
patterns, use `ugrep -U` to disable full Unicode pattern matching.
In fact, executing `ugrep` with options `-U`, `-Y`, `-.` and `--sort` makes it
behave exactly like `egrep`, matching only ASCII/LATIN1 non-UTF Unicode
patterns, permitting empty patterns to match and search hidden files instead of
ignoring them, respectively. See [grep equivalence](#equivalence).
- You can create [convenient grep aliases](#aliases) with or without options
`-U`, `-Y`, `-.` and `--sort` or include other options as desired.
- Or you can create `grep`, `egrep` and `fgrep` executables by copying `ugrep`
to those names. When the `ugrep` (or `ugrep.exe`) executable is copied as
`grep` (`grep.exe`), `egrep` (`egrep.exe`), `fgrep` (`fgrep.exe`), then
option `-U`, `-Y` and `-.` are automatically enabled together with either
`-G` for `grep`, `-E` for `egrep` and `-F` for `fgrep`. In addition, when
copied as `zgrep`, `zegrep` and `zfgrep`, option `-z` is enabled. For
example, when `ugrep` is copied as `zegrep`, options `-z`, `-E`, `-Y`, `-.`
and `--sort` are enabled.
- Likewise, symlinks and hard links to `ugrep` work fine too to create `grep`,
`egrep` and `fgrep` replacements. For example, to create a symlink `egrep`:
sudo ln -s `which ugrep` /opt/local/bin/egrep
The `/opt/local/bin` is just an example and may or may not be in your `$path`
and may or may not be found when executing `egrep` depending on your `$path`.
<a name="equivalence"/>
### Equivalence to GNU/BSD grep
**ugrep** is equivalent to GNU/BSD grep when the following options are used:
grep = ugrep -G -U -Y -. --sort -Dread -dread
egrep = ugrep -E -U -Y -. --sort -Dread -dread
fgrep = ugrep -F -U -Y -. --sort -Dread -dread
zgrep = ugrep -z -G -U -Y -. --sort -Dread -dread
zegrep = ugrep -z -E -U -Y -. --sort -Dread -dread
zfgrep = ugrep -z -F -U -Y -. --sort -Dread -dread
where:
- `-U` disables Unicode wide-character pattern matching, so for example the
pattern `\xa3` matches byte A3 instead of the Unicode code point U+00A3
represented by the UTF-8 sequence C2 A3. By default in ugrep, `\xa3` matches
U+00A3. We do not recommend to use `-U` for text pattern searches, only for
binary searches or to search latin-1 (iso-8859-1) files without reporting
these files as binary (since ugrep v3.5.0).
- `-Y` enables empty matches, so for example the pattern `a*` matches every
line instead of a sequence of `a`'s. By default in ugrep, the pattern `a*`
matches a sequence of `a`'s. Moreover, in ugrep the pattern `a*b*c*` matches
what it is supposed to match by default. See [improvements](#improvements).
- `-.` searches hidden files (dotfiles). By default, hidden files are ignored,
like most Unix utilities.
- `--sort` specifies output sorted by pathname, showing sorted matching files
first followed by sorted recursive matches in subdirectories. Otherwise,
matching files are reported in no particular order to improve performance;
- `-Dread` and `-dread` are the GNU/BSD grep defaults but are not recommended,
see [improvements](#improvements) for an explanation.
🔝 [Back to table of contents](#toc)
<a name="aliases"/>
### Short and quick command aliases
Commonly-used aliases to add to `.bashrc` to increase productivity:
alias uq = 'ug -Q' # short & quick query TUI (interactive, uses .ugrep config)
alias ux = 'ug -UX' # short & quick binary pattern search (uses .ugrep config)
alias uz = 'ug -z' # short & quick compressed files and archives search (uses .ugrep config)
alias ugit = 'ug -R --ignore-files' # works like git-grep & define your preferences in .ugrep config
alias grep = 'ugrep -G' # search with basic regular expressions (BRE)
alias egrep = 'ugrep -E' # search with extended regular expressions (ERE)
alias fgrep = 'ugrep -F' # find string(s)
alias pgrep = 'ugrep -P' # search with Perl regular expressions
alias xgrep = 'ugrep -W' # search (ERE) and output text or hex for binary
alias zgrep = 'ugrep -zG' # search compressed files and archives with BRE
alias zegrep = 'ugrep -zE' # search compressed files and archives with ERE
alias zfgrep = 'ugrep -zF' # find string(s) in compressed files and/or archives
alias zpgrep = 'ugrep -zP' # search compressed files and archives with Perl regular expressions
alias zxgrep = 'ugrep -zW' # search (ERE) compressed files/archives and output text or hex for binary
alias xdump = 'ugrep -X ""' # hexdump files without searching
To search PDF and office documents automatically, add a filter option to the
aliased `ugrep` command:
--filter="pdf:pdftotext % -,odt,doc,docx,rtf,xls,xlsx,ppt,pptx:soffice --headless --cat %"
This requires the utilities [`pdftotext`](https://pypi.org/project/pdftotext)
and [`soffice`](https://www.libreoffice.org) to be installed. See
[Using filter utilities to search documents with --filter](#filter).
🔝 [Back to table of contents](#toc)
<a name="improvements"/>
### Notable improvements over grep
- **ugrep** starts an interactive query TUI with option `-Q`.
- **ugrep** matches patterns across multiple lines when patterns match `\n`.
- **ugrep** matches full Unicode by default (disabled with option `-U`).
- **ugrep** supports fuzzy (approximate) matching with option `-Z`.
- **ugrep** supports gitignore with option `--ignore-files`.
- **ugrep** supports user-defined global and local configuration files.
- **ugrep** supports Boolean patterns with AND, OR and NOT (option `--bool`).
- **ugrep** searches compressed files and archives with option `-z`.
- **ugrep** searches cpio, jar, pax, tar and zip archives with option `-z`.
- **ugrep** searches cpio, jar, pax, tar and zip archives recursively stored
within archives with `-z` and `--zmax=NUM` for up to `NUM` levels deep.
- **ugrep** searches pdf, doc, docx, xls, xlsx, epub, and more with `--filter`
using third-party format conversion utilities as plugins.
- **ugrep** searches a directory when the FILE argument is a directory, like
most Unix/Linux utilities; use option `-r` to search directories recursively.
- **ugrep** does not match hidden files by default like most Unix/Linux
utilities (hidden dotfile file matching is enabled with `-.`).
- **ugrep** regular expression patterns are more expressive than GNU grep and
BSD grep POSIX ERE and support Unicode pattern matching. Extended regular
expression (ERE) syntax is the default (i.e. option `-E` as egrep, whereas
`-G` enables BRE).
- **ugrep** spawns threads to search files concurrently to improve search
speed (disabled with option `-J1`).
- **ugrep** produces hexdumps with `-W` (output binary matches in hex with text
matches output as usual) and `-X` (output all matches in hex).
- **ugrep** can output matches in JSON, XML, CSV and user-defined formats (with
option `--format`).
- **ugrep** option `-f` uses `GREP_PATH` environment variable or the predefined
patterns installed in `/usr/local/share/ugrep/patterns`. If `-f` is
specified and also one or more `-e` patterns are specified, then options
`-F`, `-x`, and `-w` do not apply to `-f` patterns. This is to avoid
confusion when `-f` is used with predefined patterns that may no longer work
properly with these options.
- **ugrep** options `-O`, `-M`, and `-t` specify file extensions, file
signature magic byte patterns, and predefined file types, respectively. This
allows searching for certain types of files in directory trees, for example
with recursive search options `-R` and `-r`. Options `-O`, `-M`, and `-t`
also applies to archived files in cpio, jar, pax, tar, and zip files.
- **ugrep** option `-k`, `--column-number` to display the column number, taking
tab spacing into account by expanding tabs, as specified by option `--tabs`.
- **ugrep** option `-P` (Perl regular expressions) supports backreferences
(with `--format`) and lookbehinds, which uses the PCRE2 or Boost.Regex
library for fast Perl regex matching with a PCRE-like syntax.
- **ugrep** option `-b` with option `-o` or with option `-u`, ugrep displays
the exact byte offset of the pattern match instead of the byte offset of the
start of the matched line reported by GNU/BSD grep.
- **ugrep** option `-u`, `--ungroup` to not group multiple matches per line.
This option displays a matched input line again for each additional pattern
match on the line. This option is particularly useful with option `-c` to
report the total number of pattern matches per file instead of the number of
lines matched per file.
- **ugrep** option `-Y` enables matching empty patterns. Grepping with
empty-matching patterns is weird and gives different results with GNU grep
versus BSD grep. Empty matches are not output by **ugrep** by default, which
avoids making mistakes that may produce "random" results. For example, with
GNU/BSD grep, pattern `a*` matches every line in the input, and actually
matches `xyz` three times (the empty transitions before and between the `x`,
`y`, and `z`). Allowing empty matches requires **ugrep** option `-Y`.
Patterns that start with `^` or end with `$`, such as `^\h*$`, match empty.
These patterns automatically enable option `-Y`.
- **ugrep** option `-D, --devices=ACTION` is `skip` by default, instead of
`read`. This prevents unexpectedly hanging on named pipes in directories
that are recursively searched, as may happen with GNU/BSD grep that `read`
devices by default.
- **ugrep** option `-d, --directories=ACTION` is `skip` by default, instead of
`read`. By default, directories specified on the command line are searched,
but not recursively deeper into subdirectories.
- **ugrep** offers *negative patterns* `-N PATTERN`, which are patterns of the
form `(?^X)` that skip all `X` input, thus removing `X` from the search.
For example, negative patterns can be used to skip strings and comments when
searching for identifiers in source code and find matches that aren't in
strings and comments. Predefined `zap` patterns use negative patterns, for
example, use `-f cpp/zap_comments` to ignore pattern matches in C++ comments.
- **ugrep** does not the `GREP_OPTIONS` environment variable, because the
behavior of **ugrep** must be portable and predictable on every system. Also
GNU grep abandoned `GREP_OPTIONS` for this reason. Please use the `ug`
command that loads the .ugrep configuration file located in the working
directory or in the home directory when present, or use shell aliases to
create new commands with specific search options.
🔝 [Back to table of contents](#toc)
<a name="tutorial"/>
Tutorial
--------
<a name="examples"/>
### Examples
To perform a search using a configuration file `.ugrep` placed in the working
directory or home directory (note that `ug` is the same as `ugrep --config`):
ug PATTERN FILE...
To save a `.ugrep` configuration file to the working directory, then edit this
file in your home directory to customize your preferences for `ug` defaults:
ug --save-config
To search the working directory and recursively deeper for `main` (note that
`-r` recurse symlinks is enabled by default if no file arguments are
specified):
ug main
Same, but only search C++ source code files recursively, ignoring all other
files:
ug -tc++ main
Same, using the interactive query TUI, starting with the initial search pattern
`main` (note that `-Q` with an initial pattern requires option `-e` because
patterns are normally specified interactively and all command line arguments
are considered files/directories):
ug -Q -tc++ -e main
To search for `#define` (and `# define` etc) using a regex pattern in C++ files
(note that patterns should be quoted to prevent shell globbing of `*` and `?`):
ug -tc++ '#[\t ]*define'
To search for `main` as a word (`-w`) recursively without following symlinks
(`-r`) in directory `myproject`, showing the matching line (`-n`) and column
(`-k`) numbers next to the lines matched:
ug -r -nkw main myproject
Same, but only search `myproject` without recursing deeper (note that directory
arguments are searched at one level by default):
ug -nkw main myproject
Same, but search `myproject` and one subdirectory level deeper (two levels)
with `-2`:
ug -2 -nkw main myproject
Same, but only search C++ files in `myproject` and its subdirectories with
`-tc++`:
ug -tc++ -2 -nkw main myproject
Same, but also search inside archives (e.g. zip and tar files) and compressed
files with `-z`:
ug -z -tc++ -2 -nkw main myproject
Search recursively the working directory for `main` while ignoring gitignored
files (e.g. assuming `.gitignore` is in the working directory or below):
ug --ignore-files -tc++ -nkw main
To list all files in the working directory and deeper that are not ignored by
`.gitignore` file(s):
ug --ignore-files -l ''
To display the list of file name extensions and "magic bytes" (shebangs)
that are searched corresponding to `-t` arguments:
ug -tlist
To list all shell files recursively, based on extensions and shebangs with `-l`
(note that `''` matches any non-empty file):
ug -l -tShell ''
🔝 [Back to table of contents](#toc)
<a name="advanced"/>
### Advanced examples
To search for `main` in source code while ignoring strings and comment blocks
we can use *negative patterns* with option `-N` to skip unwanted matches in
C/C++ quoted strings and comment blocks:
ug -r -nkw -e 'main' -N '"(\\.|\\\r?\n|[^\\\n"])*"|//.*|/\*([^*]|\n|(\*+([^*/]|\n)))*\*+\/' myproject
This is a lot of work to type in correctly! If you are like me, I don't want
to spend time fiddling with regex patterns when I am working on something more
important. There is an easier way by using **ugrep**'s predefined patterns
(`-f`) that are installed with the `ugrep` tool:
ug -r -nkw 'main' -f c/zap_strings -f c/zap_comments myproject
This query also searches through other files than C/C++ source code, like
READMEs, Makefiles, and so on. We're also skipping symlinks with `-r`. So
let's refine this query by selecting C/C++ files only using option `-tc,c++`
and include symlinks to files and directories with `-R`:
ug -R -tc,c++ -nkw 'main' -f c/zap_strings -f c/zap_comments myproject
What if we are only looking for the identifier `main` but not as a function
`main(`? We can use a negative pattern for this to skip unwanted `main\h*(`
pattern matches:
ug -R -tc,c++ -nkw -e 'main' -N 'main\h*\(' -f c/zap_strings -f c/zap_comments myproject
This uses the `-e` and `-N` options to explicitly specify a pattern and a
negative pattern, respectively, which is essentially forming the pattern
`main|(?^main\h*\()`, where `\h` matches space and tab. In general, negative
patterns are useful to filter out pattern matches we are not interested in.
As another example, we may want to search for the word `FIXME` in C/C++ comment
blocks. To do so we can first select the comment blocks with **ugrep**'s
predefined `c/comments` pattern AND THEN select lines with `FIXME` using a
pipe:
ug -R -tc,c++ -nk -f c/comments myproject | ug -w 'FIXME'
Filtering results with pipes is generally easier than using AND-OR logic that
some search tools use. This approach follows the Unix spirit to keep utilities
simple and use them in combination for more complex tasks.
Say we want to produce a sorted list of all identifiers found in Java source
code while skipping strings and comments:
ug -R -tjava -f java/names myproject | sort -u
This matches Java Unicode identifiers using the regex
`\p{JavaIdentifierStart}\p{JavaIdentifierPart}*` defined in
`patterns/java/names`.
With traditional grep and grep-like tools it takes great effort to recursively
search for the C/C++ source file that defines function `qsort`, requiring
something like this:
ug -R --include='*.c' --include='*.cpp' '^([ \t]*[[:word:]:*&]+)+[ \t]+qsort[ \t]*\([^;\n]+$' myproject
Fortunately, with **ugrep** we can simply select all function definitions in
files with extension `.c` or `.cpp` by using option `-Oc,cpp` and by using a
predefined pattern `functions` that is installed with the tool to produce
all function definitions. Then we select the one we want:
ug -R -Oc,cpp -nk -f c/functions | ug 'qsort'
Note that we could have used `-tc,c++` to select C/C++ files, but this also
includes header files when we want to only search `.c` and `.cpp` files.
We can also skip files and directories from being searched that are defined in
`.gitignore`. To do so we use `--ignore-files` to exclude any files and
directories from recursive searches that match the globs in `.gitignore`, when
one ore more`.gitignore` files are found:
ug -R -tc++ --ignore-files -f c++/defines
This searches C++ files (`-tc++`) in the working directory for `#define`
lines (`-f c++/defines`), while skipping files and directories declared in
`.gitignore`. If you find this too long to type then define an alias to search
GitHub directories:
alias ugit='ugrep -R --ignore-files'
ugit -tc++ -f c++/defines
To highlight matches when pushed through a chain of pipes we should use
`--color=always`:
ugit --color=always -tc++ -f c++/defines | ugrep -w 'FOO.*'
This returns a color-highlighted list of all `#define FOO...` macros in C/C++
source code files, skipping files defined in `.gitignore`.
Note that the complement of `--exclude` is not `--include`, because exclusions
always take precedence over inclusions, so we cannot reliably list the files
that are ignored with `--include-from='.gitignore'`. Only files explicitly
specified with `--include` and directories explicitly specified with
`--include-dir` are visited. The `--include-from` from lists globs that are
considered both files and directories to add to `--include` and
`--include-dir`, respectively. This means that when directory names and
directory paths are not explicitly listed in this file then it will not be
visited using `--include-from`.
Because ugrep checks if the input is valid UTF-encoded Unicode (unless `-U` is
used), it is possible to use it as a filter to ignore non-UTF output produced
by a program:
program | ugrep -I ''
If the program produces valid output then the output is passed through,
otherwise the output is filtered out option `-I`. If the output is initially
valid for a very large portion but is followed by invalid output, then ugrep
may initially show the output up to but excluding the invalid output after
which further output is blocked.
To filter lines that are valid ASCII or UTF-encoded, while removing lines that
are not:
program | ugrep '[\p{Unicode}--[\n]]+'
Note that `\p{Unicode}` matches `\n` but we don't want to matche the whole
file! Just lines with `[\p{Unicode}--[\n]]+`.
🔝 [Back to table of contents](#toc)
<a name="help"/>
### Displaying helpful info
The ugrep man page:
man ugrep
To show a help page:
ug --help
To show options that mention `WHAT`:
ug --help WHAT
To show a list of `-t TYPES` option values:
ug -tlist
In the interactive query TUI, press F1 or CTRL-Z for help and options:
ug -Q
🔝 [Back to table of contents](#toc)
<a name="config"/>
### Configuration files
--config[=FILE], ---[FILE]
Use configuration FILE. The default FILE is `.ugrep'. The working
directory is checked first for FILE, then the home directory. The
options specified in the configuration FILE are parsed first,
followed by the remaining options specified on the command line.
--save-config[=FILE]
Save configuration FILE. By default `.ugrep' is saved. If FILE is
a `-', write the configuration to standard output.
#### The ug command versus the ugrep command
The `ug` command is intended for context-dependent interactive searching and is
equivalent to the `ugrep --config` command to load the configuration file
`.ugrep` when present in the working directory or, when not found, in the home
directory:
ug PATTERN ...
ugrep --config PATTERN ...
The `ug` command also sorts files by name per directory searched. A
configuration file contains `NAME=VALUE` pairs per line, where `NAME` is the
name of a long option (without `--`) and `=VALUE` is an argument, which is
optional and may be omitted depending on the option. Empty lines and lines
starting with a `#` are ignored:
# Color scheme
colors=cx=hb:ms=hiy:mc=hic:fn=hi+y+K:ln=hg:cn=hg:bn=hg:se=
# Disable searching hidden files and directories
no-hidden
# ignore files specified in .ignore and .gitignore in recursive searches
ignore-files=.ignore
ignore-files=.gitignore
Command line options are parsed in the following order: first the (default or
named) configuration file is loaded, then the remaining options and
arguments on the command line are parsed.
Option `--stats` displays the configuration file used after searching.
#### Named configuration files
Named configuration files are intended to streamline custom search tasks, by
reducing the number of command line options to just one `---FILE` to use the
collection of options specified in `FILE`. The `--config=FILE` option and its
abbreviated form `---FILE` load the specified configuration file located in the
working directory or, when not found, located in the home directory:
ug ---FILE PATTERN ...
ugrep ---FILE PATTERN ...
An error is produced when `FILE` is not found or cannot be read.
Named configuration files can be used to define a collection of options that
are specific to the requirements of a task in the development workflow of a
project. For example to report unresolved issues by checking the source code
and documentation for comments with FIXME and TODO items. Such named
configuration file can be localized to a project by placing it in the project
directory, or it can be made global by placing it in the home directory. For
visual feedback, a color scheme specific to this task can be specified with
option `colors` in the configuration `FILE` to help identify the output
produced by a named configuration as opposed to the default configuration.
#### Saving a configuration file
The `--save-config` option saves a `.ugrep` configuration file to the
working directory. The file contains a strict subset of options that are
deemed reasonably safe with respect to the search results reported.
The `--save-config=FILE` option saves the configuration to the specified `FILE`.
The configuration is written to standard output when `FILE` is a `-`.
🔝 [Back to table of contents](#toc)
<a name="query"/>
### Interactive search with -Q
-Q[DELAY], --query[=DELAY]
Query mode: user interface to perform interactive searches. This
mode requires an ANSI capable terminal. An optional DELAY argument
may be specified to reduce or increase the response time to execute
searches after the last key press, in increments of 100ms, where
the default is 5 (0.5s delay). No whitespace may be given between
-Q and its argument DELAY. Initial patterns may be specified with
-e PATTERN, i.e. a PATTERN argument requires option -e. Press F1
or CTRL-Z to view the help screen. Press F2 or CTRL-Y to invoke a
command to view or edit the file shown at the top of the screen.
The command can be specified with option --view, or defaults to
environment variable PAGER if defined, or EDITOR. Press Tab and
Shift-Tab to navigate directories and to select a file to search.
Press Enter to select lines to output. Press ALT-l for option -l
to list files, ALT-n for -n, etc. Non-option commands include
ALT-] to increase fuzziness and ALT-} to increase context. Enables
--heading. See also options --confirm and --view.
--no-confirm
Do not confirm actions in -Q query mode. The default is confirm.
--view[=COMMAND]
Use COMMAND to view/edit a file in query mode when pressing CTRL-Y.
This option starts a user interface to enter search patterns interactively:
- Press F1 or CTRL-Z to view a help screen and to enable or disable options.
- Press Alt with a key corresponding to a ugrep option letter or digit to
enable or disable the ugrep option. For example, pressing Alt-c enables
option `-c` to count matches. Pressing Alt-c again disables `-c`. Options
can be toggled with the Alt key while searching or when viewing the help
screen. If Alt/Meta keys are not supported (e.g. X11 xterm), then press
CTRL-O followed by the key corresponding to the option.
- Press Alt-g to enter or edit option `-g` file and directory matching globs, a
comma-separated list of gitignore-style glob patterns. Presssing ESC returns
control to the query pattern prompt (the globs are saved). When a glob is
preceded by a `!` or a `^`, skips files whose name matches the glob When a
glob contains a `/`, full pathnames are matched. Otherwise basenames are
matched. When a glob ends with a `/`, directories are matched.
- The query TUI prompt switches between `Q>` (normal), `F>` (fixed strings),
`G>` (basic regex), `P>` (Perl matching), and `Z>` (fuzzy matching).
When the `--glob=` prompt is shown, a comma-separated list of gitignore-style
glob patterns may be entered. Presssing ESC returns control to the pattern
prompt.
- Press Enter to switch to selection mode to select lines to output when ugrep
exits. Normally, ugrep in query mode does not output any results unless
results are selected. While in selection mode, select or deselect lines with
Enter or Del, or press A to select all results.
- The file listed or shown at the top of the screen, or beneath the cursor in
selection mode, is edited by pressing F2 or CTRL-Y. A file viewer or editor
may be specified with `--view=COMMAND`. Otherwise, the `PAGER` or `EDITOR`
environment variables are used to invoke the command with CTRL-Y. Filenames
must be enabled and visible in the output to use this feature.
- Press TAB to chdir one level down into the directory of the file listed
or viewed at the top of the screen. If no directory exists, the file itself
is selected to search. Press Shift-TAB to go back up one level.
- Press CTRL-T to toggle colors on and off. Normally ugrep in query mode uses
colors and other markup to highlight results. When colors are turned off,
selected results are also not colored in the output produced by ugrep when
ugrep exits. When colors are turned on (the default), selected results are
colored depending on the `--color` option.
- The query engine is optimized to limit system load by performing on-demand
searches to produce results only for the visible parts shown in the
interface. That is, results are shown on demand, when scrolling down and
when exiting when all results are selected. When the search pattern is
modified, the previous search query is cancelled when incomplete. This
effectively limits the load on the system to maintain a high degree of
responsiveness of the query engine to user input. Because the search results
are produced on demand, occasionally you may notice a flashing "Searching..."
message when searching files.
- To display results faster, specify a low `DELAY` value such as 1. However,
lower values may increase system load as a result of repeatedly initiating
and cancelling searches by each key pressed.
- To avoid long pathnames to obscure the view, `--heading` is enabled by
default. Press Alt-+ to switch headings off.
Query TUI key mapping:
key(s) | function
----------------------- | -------------------------------------------------
`Alt-key` | toggle ugrep command-line option corresponding to `key`
`Alt-/`xxxx`/` | insert Unicode hex code point U+xxxx
`Esc` `Ctrl-[` `Ctrl-C` | go back or exit
`Ctrl-Q` | quick exit and output the results selected in selection mode
`Tab` | chdir to the directory of the file shown at the top of the screen or select file
`Shift-Tab` | chdir one level up or deselect file
`Enter` | enter selection mode and toggle selected lines to output on exit
`Up` `Ctrl-P` | move up
`Down` `Ctrl-N` | move down
`Left` `Ctrl-B` | move left
`Right` `Ctrl-F` | move right
`PgUp` `Ctrl-G` | move display up by a page
`PgDn` `Ctrl-D` | move display down by a page
`Alt-Up` | move display up by 1/2 page (MacOS `Shift-Up`)
`Alt-Down` | move display down by 1/2 page (MacOS `Shift-Down`)
`Alt-Left` | move display left by 1/2 page (MacOS `Shift-Left`)
`Alt-Right` | move display right by 1/2 page (MacOS `Shift-Right`)
`Home` `Ctrl-A` | move cursor to the beginning of the line
`End` `Ctrl-E` | move cursor to the end of the line
`Ctrl-K` | delete after cursor
`Ctrl-L` | refresh screen
`Ctrl-O`+`key` | toggle ugrep command-line option corresponding to `key`, same as `Alt-key`
`Ctrl-R` `F4` | jump to bookmark
`Ctrl-S` | scroll to the next file
`Ctrl-T` | toggle colors on/off
`Ctrl-U` | delete before cursor
`Ctrl-V` | verbatim character
`Ctrl-W` | scroll back one file
`Ctrl-X` `F3` | set bookmark
`Ctrl-Y` `F2` | edit file shown at the top of the screen or under the cursor
`Ctrl-Z` `F1` | view help and options
`Ctrl-^` | chdir back to the starting working directory
`Ctrl-\` | terminate process
To interactively search the files in the working directory and below:
ug -Q
Same, but restricted to C++ files only and ignoring `.gitignore` files:
ug -Q -tc++ --ignore-files
To interactively search all makefiles in the working directory and below:
ug -Q -g 'Makefile*' -g 'makefile*'
Same, but for up to 2 directory levels (working and one subdirectory level):
ug -Q -2 -g 'Makefile*' -g 'makefile*'
To interactively view the contents of `main.cpp` and search it, where `-y`
shows any nonmatching lines as context:
ug -Q -y main.cpp
To interactively search `main.cpp`, starting with the search pattern `TODO` and
a match context of 5 lines (context can be interactively enabled and disabled,
this also overrides the default context size of 2 lines):
ug -Q -C5 -e TODO main.cpp
To view and search the contents of an archive (e.g. zip, tarball):
ug -Q -z archive.tar.gz
To interactively select files from `project.zip` to decompress with `unzip`,
using ugrep query selection mode (press Enter to select lines):
unzip project.zip `zipinfo -1 project.zip | ugrep -Q`
🔝 [Back to table of contents](#toc)
<a name="recursion"/>
### Recursively list matching files with -l, -R, -r, --depth, -g, -O, and -t
-L, --files-without-match
Only the names of files not containing selected lines are written
to standard output. Pathnames are listed once per file searched.
If the standard input is searched, the string ``(standard input)''
is written. If --tree is specified, outputs directories in a
tree-like format.
-l, --files-with-matches
Only the names of files containing selected lines are written to
standard output. ugrep will only search a file until a match has
been found, making searches potentially less expensive. Pathnames
are listed once per file searched. If the standard input is
searched, the string ``(standard input)'' is written. If --tree is
specified, outputs directories in a tree-like format.
-R, --dereference-recursive
Recursively read all files under each directory. Follow all
symbolic links, unlike -r. See also option --sort.
-r, --recursive
Recursively read all files under each directory, following symbolic
links only if they are specified on the command line. Note that
when no FILE arguments are specified and input is read from a
terminal, recursive searches are performed as if -r is specified.
See also option --sort.
--depth=[MIN,][MAX], -1, -2, -3, ... -9, --10, --11, --12, ...
Restrict recursive searches from MIN to MAX directory levels deep,
where -1 (--depth=1) searches the specified path without recursing
into subdirectories. Note that -3 -5, -3-5, and -35 search 3 to 5
levels deep. Enables -r if -R or -r is not specified.
-g GLOBS, --glob=GLOBS
Search only files whose name matches the specified comma-separated
list of GLOBS, same as --include='glob' for each `glob' in GLOBS.
When a `glob' is preceded by a `!' or a `^', skip files whose name
matches `glob', same as --exclude='glob'. When `glob' contains a
`/', full pathnames are matched. Otherwise basenames are matched.
When `glob' ends with a `/', directories are matched, same as
--include-dir='glob' and --exclude-dir='glob'. A leading `/'
matches the working directory. This option may be repeated and may
be combined with options -M, -O and -t to expand searches. See
`ugrep --help globs' and `man ugrep' section GLOBBING for details.
-O EXTENSIONS, --file-extension=EXTENSIONS
Search only files whose filename extensions match the specified
comma-separated list of EXTENSIONS, same as --include='*.ext' for
each `ext' in EXTENSIONS. When `ext' is preceded by a `!' or a
`^', skip files whose filename extensions matches `ext', same as
--exclude='*.ext'. This option may be repeated and may be combined
with options -g, -M and -t to expand the recursive search.
-t TYPES, --file-type=TYPES
Search only files associated with TYPES, a comma-separated list of
file types. Each file type corresponds to a set of filename
extensions passed to option -O and filenames passed to option -g.
For capitalized file types, the search is expanded to include files
with matching file signature magic bytes, as if passed to option
-M. When a type is preceded by a `!' or a `^', excludes files of
the specified type. This option may be repeated.
--stats
Output statistics on the number of files and directories searched,
and the inclusion and exclusion constraints applied.
If no FILE arguments are specified and input is read from a terminal, recursive
searches are performed as if `-r` is specified. To force reading from standard
input, specify `-` as the FILE argument.
To recursively list all non-empty files in the working directory, following
symbolic links:
ug -r -l ''
To list all non-empty files in the working directory but not deeper (since a
FILE argument is given, in this case `.` for the working directory):
ug -l '' .
To list all non-empty files in directory `mydir` but not deeper (since a FILE
argument is given):
ug -l '' mydir
To list all non-empty files in directory `mydir` and deeper while following
symlinks:
ug -R -l '' mydir
To recursively list all non-empty files on the path specified, while visiting
subdirectories only, i.e. directories `mydir/` and subdirectories at one
level deeper `mydir/*/` are visited (note that `-2 -l` can be abbreviated to
`-l2`):
ug -2 -l '' mydir
To recursively list all non-empty files in directory `mydir`, not following any
symbolic links (except when on the command line such as `mydir`):
ug -rl '' mydir
To recursively list all Makefiles matching the text `CPP`:
ug -l -tmake 'CPP'
To recursively list all `Makefile.*` matching `bin_PROGRAMS`:
ug -l -g'Makefile.*' 'bin_PROGRAMS'
To recursively list all non-empty files with extension .sh, with `-Osh`:
ug -l -Osh ''
To recursively list all shell scripts based on extensions and shebangs with
`-tShell`:
ug -l -tShell ''
To recursively list all shell scripts based on extensions only with `-tshell`:
ug -l -tshell ''
🔝 [Back to table of contents](#toc)
<a name="bool"/>
### Boolean query patterns with --bool (-%), --and, --not
--bool, -%
Specifies Boolean query patterns. A Boolean query pattern is
composed of `AND', `OR', `NOT' operators and grouping with `(' `)'.
Spacing between subpatterns is the same as `AND', `|' is the same
as `OR' and a `-' is the same as `NOT'. The `OR' operator binds
more tightly than `AND'. For example, --bool 'A|B C|D' matches
lines with (`A' or `B') and (`C' or `D'), --bool 'A -B' matches
lines with `A' and not `B'. Operators `AND', `OR', `NOT' require
proper spacing. For example, --bool 'A OR B AND C OR D' matches
lines with (`A' or `B') and (`C' or `D'), --bool 'A AND NOT B'
matches lines with `A' without `B'. Quoted subpatterns are matched
literally as strings. For example, --bool 'A "AND"|"OR"' matches
lines with `A' and also either `AND' or `OR'. Parenthesis are used
for grouping. For example, --bool '(A B)|C' matches lines with `A'
and `B', or lines with `C'. Note that all subpatterns in a Boolean
query pattern are regular expressions, unless -F is specified.
Options -E, -F, -G, -P and -Z can be combined with --bool to match
subpatterns as strings or regular expressions (-E is the default.)
This option does not apply to -f FILE patterns. Option --stats
displays the search patterns applied. See also options --and,
--andnot, --not, --files and --lines.
--files
Apply Boolean queries to match files, the opposite of --lines. A
file matches if all Boolean conditions are satisfied by the lines
matched in the file. For example, --files -e A --and -e B -e C
--andnot -e D matches a file if some lines match `A' and some lines
match (`B' or `C') and no line in the file matches `D'. May also
be specified as --files --bool 'A B|C -D'. Option -v cannot be
specified with --files. See also options --and, --andnot, --not,
--bool and --lines.
--lines
Apply Boolean queries to match lines, the opposite of --files.
This is the default Boolean query mode to match specific lines.
--and [[-e] PATTERN] ... -e PATTERN
Specify additional patterns to match. Patterns must be specified
with -e. Each -e PATTERN following this option is considered an
alternative pattern to match, i.e. each -e is interpreted as an OR
pattern. For example, -e A -e B --and -e C -e D matches lines with
(`A' or `B') and (`C' or `D'). Note that multiple -e PATTERN are
alternations that bind more tightly together than --and. Option
--stats displays the search patterns applied. See also options
--not, --andnot, and --bool.
--andnot [[-e] PATTERN] ...
Combines --and --not. See also options --and, --not, and --bool.
--not [-e] PATTERN
Specifies that PATTERN should not match. Note that -e A --not -e B
matches lines with `A' or lines without a `B'. To match lines with
`A' that have no `B', specify -e A --andnot -e B. Option --stats
displays the search patterns applied. See also options --and,
--andnot, and --bool.
--stats
Output statistics on the number of files and directories searched,
and the inclusion and exclusion constraints applied.
Note that the `--and`, `--not`, and `--andnot` options require `-e PATTERN`.
The `--bool` option makes all patterns Boolean-based, supporting the following
logical operations listed from the highest level of precedence to the lowest:
operator | alternative | result
-------- | ----------- | -------
`"x"` | | match `x` literally and exactly as specified (using the standard regex escapes `\Q` and `\E`)
`( )` | | Boolean expression grouping
`-x` | `NOT x` | inverted match, i.e. matches if `x` does not match
`x\|y` | `x OR y` | matches lines with `x` or `y`
`x y` | `x AND y` | matches lines with both `x` and `y`
- `x` and `y` are subpatterns that do not start with the special symbols `|`,
`-`, and `(` (use quotes or a `\` escape to match these);
- `-` and `NOT` are the same and take precedence over `OR`, which means that
`-x|y` == `(-x)|y` for example.
- `|` and `OR` are the same and take precedence over `AND`, which means that
`x y|z` == `x (y|z)` for example;
The `--stats` option displays the Boolean queries in human-readable form
converted to CNF (Conjunctive Normal Form), after the search is completed.
To show the CNF without a search, read from standard input terminated by an
EOF, like `echo | ugrep --bool '...' --stats`.
Subpatterns are color-highlighted in the output, except those negated with
`NOT` (a `NOT` subpattern may still show up in a matching line when using an
OR-NOT pattern like `x|-y`). Note that subpatterns may overlap. In that
case only the first matching subpattern is color-highlighted.
Multiple lines may be matched when subpatterns match newlines. There is one
exception however: subpatterns ending with `(?=X)` lookaheads may not match
when `X` spans multiple lines.
Empty patterns match any line (grep standard). Therefore, `--bool 'x|""|y'`
matches everything and `x` and `y` are not color-highlighted. Option `-y`
should be used to show every line as context, for example `-y 'x|y'`.
Fzf-like interactive querying (Boolean search with fixed strings with fuzzy
matching to allow e.g. up to 4 extra characters matched with `-Z+4` in words
with `-w`), press TAB and ALT-y to view a file with matches. Press SHIFT-TAB
and ALT-l to go back to the list of matching files:
ug -Q1 --bool -l -w -F -Z+4 --sort=best
To recursively find all files containing both `hot` and `dog` anywhere in the
file with option `--files`:
ug --files --bool 'hot dog'
ug --files -e hot --and dog
To find lines containing both `hot` and `dog` in `myfile.txt`:
ug --bool 'hot dog' myfile.txt
ug -e hot --and dog myfile.txt
To find lines containing `place` and then also `hotdog` or `taco` (or both) in
`myfile.txt`:
ug --bool 'hotdog|taco place' myfile.txt
ug -e hotdog -e taco --and place myfile.txt
Same, but exclude lines matching `diner`:
ug --bool 'hotdog|taco place -diner' myfile.txt
ug -e hotdog -e taco --and place --andnot diner myfile.txt
To find lines with `diner` or lines that match both `fast` and `food` but not `bad` in `myfile.txt`:
ug --bool 'diner|(fast food -bad)' myfile.txt
To find lines with `fast food` (exactly) or lines with `diner` but not `bad` or `old` in `myfile.txt`:
ug --bool '"fast food"|diner -bad -old' myfile.txt
Same, but using a different Boolean expression that has the same meaning:
ug --bool '"fast food"|diner -(bad|old)' myfile.txt
To find lines with `diner` implying `good` in `myfile.txt` (that is, show lines
with `good` without `diner` and show lines with `diner` but only those with
`good`, which is logically implied!):
ug --bool 'good|-diner' myfile.txt
ug -e good --not diner myfile.txt
To find lines with `foo` and `-bar` and `"baz"` in `myfile.txt` (not that `-`
and `"` should be matched using `\` escapes and with `--and -e -bar`):
ug --bool 'foo \-bar \"baz\"' myfile.txt
ug -e foo --and -e -bar --and '"baz"' myfile.txt
To search `myfile.cpp` for lines with `TODO` or `FIXME` but not both on the
same line, like XOR:
ug --bool 'TODO|FIXME -(TODO FIXME)' myfile.cpp
ug -e TODO -e FIXME --and --not TODO --not FIXME myfile.cpp
🔝 [Back to table of contents](#toc)
<a name="not"/>
### Search this but not that with -v, -e, -N, -f, -L, -w, -x
-e PATTERN, --regexp=PATTERN
Specify a PATTERN used during the search of the input: an input
line is selected if it matches any of the specified patterns.
Note that longer patterns take precedence over shorter patterns.
This option is most useful when multiple -e options are used to
specify multiple patterns, when a pattern begins with a dash (`-'),
to specify a pattern after option -f or after the FILE arguments.
-f FILE, --file=FILE
Read newline-separated patterns from FILE. White space in patterns
is significant. Empty lines in FILE are ignored. If FILE does not
exist, the GREP_PATH environment variable is used as path to FILE.
If that fails, looks for FILE in /usr/local/share/ugrep/pattern.
When FILE is a `-', standard input is read. This option may be
repeated.
-L, --files-without-match
Only the names of files not containing selected lines are written
to standard output. Pathnames are listed once per file searched.
If the standard input is searched, the string ``(standard input)''
is written.
-N PATTERN, --neg-regexp=PATTERN
Specify a negative PATTERN used during the search of the input: an
input line is selected only if it matches the specified patterns
unless it matches the negative PATTERN. Same as -e (?^PATTERN).
Negative pattern matches are essentially removed before any other
patterns are matched. Note that longer patterns take precedence
over shorter patterns. This option may be repeated.
-v, --invert-match
Selected lines are those not matching any of the specified
patterns.
-w, --word-regexp
The PATTERN is searched for as a word, such that the matching text
is preceded by a non-word character and is followed by a non-word
character. Word characters are letters, digits, and the
underscore. With option -P, word characters are Unicode letters,
digits, and underscore. This option has no effect if -x is also
specified. If a PATTERN is specified, or -e PATTERN or -N PATTERN,
then this option has no effect on -f FILE patterns to allow -f FILE
patterns to narrow or widen the scope of the PATTERN search.
-x, --line-regexp
Select only those matches that exactly match the whole line, as if
the patterns are surrounded by ^ and $. If a PATTERN is specified,
or -e PATTERN or -N PATTERN, then this option does not apply to
-f FILE patterns to allow -f FILE patterns to narrow or widen the
scope of the PATTERN search.
See also [Boolean query patterns with --bool (-%), --and, --not](#bool) for
more powerful Boolean query options than the traditional GNU/BSD grep options.
To display lines in file `myfile.sh` but not lines matching `^[ \t]*#`:
ug -v '^[ \t]*#' myfile.sh
To search `myfile.cpp` for lines with `FIXME` and `urgent`, but not `Scotty`:
ugrep FIXME myfile.cpp | ugrep urgent | ugrep -v Scotty
Same, but using `--bool` for Boolean queries:
ug --bool 'FIXME urgent -Scotty' myfile.cpp
To search for decimals using pattern `\d+` that do not start with `0` using
negative pattern `0\d+` and excluding `555`:
ug -e '\d+' -N '0\d+' -N 555 myfile.cpp
To search for words starting with `disp` without matching `display` in file
`myfile.py` by using a "negative pattern" `-N '/<display\>'` where `-N`
specifies an additional negative pattern to skip matches:
ug -e '\<disp' -N '\<display\>' myfile.py
To search for lines with the word `display` in file `myfile.py` skipping this
word in strings and comments, where `-f` specifies patterns in files which are
predefined patterns in this case:
ug -n -w 'display' -f python/zap_strings -f python/zap_comments myfile.py
To display lines that are not blank lines:
ug -x -e '.*' -N '\h*' myfile.py
Same, but using `-v` and `-x` with `\h*`, i.e. pattern `^\h*$`:
ug -v -x '\h*' myfile.py
To recursively list all Python files that do not contain the word `display`,
allowing the word to occur in strings and comments:
ug -RL -tPython -w 'display' -f python/zap_strings -f python/zap_comments
🔝 [Back to table of contents](#toc)
<a name="encoding"/>
### Search non-Unicode files with --encoding
--encoding=ENCODING
The encoding format of the input. The default ENCODING is binary
and UTF-8 which are the same. Note that option -U specifies binary
PATTERN matching (text matching is the default.)
Binary, ASCII and UTF-8 files do not require this option to search them. Also
UTF-16 and UTF-32 files do not require this option to search them, assuming
that UTF-16 and UTF-32 files start with a UTF BOM
([byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark)) as usual.
Other file encodings require option `--encoding=ENCODING`:
encoding | parameter
---------------------- | --------------
ASCII | *n/a*
UTF-8 | *n/a*
UTF-16 with BOM | *n/a*
UTF-32 with BOM | *n/a*
UTF-16 BE w/o BOM | `UTF-16` or `UTF-16BE`
UTF-16 LE w/o BOM | `UTF-16LE`
UTF-32 w/o BOM | `UTF-32` or `UTF-32BE`
UTF-32 w/o BOM | `UTF-32LE`
Latin-1 | `LATIN1` or `ISO-8859-1`
ISO-8859-1 | `ISO-8859-1`
ISO-8859-2 | `ISO-8859-2`
ISO-8859-3 | `ISO-8859-3`
ISO-8859-4 | `ISO-8859-4`
ISO-8859-5 | `ISO-8859-5`
ISO-8859-6 | `ISO-8859-6`
ISO-8859-7 | `ISO-8859-7`
ISO-8859-8 | `ISO-8859-8`
ISO-8859-9 | `ISO-8859-9`
ISO-8859-10 | `ISO-8859-10`
ISO-8859-11 | `ISO-8859-11`
ISO-8859-13 | `ISO-8859-13`
ISO-8859-14 | `ISO-8859-14`
ISO-8859-15 | `ISO-8859-15`
ISO-8859-16 | `ISO-8859-16`
MAC (CR=newline) | `MAC`
MacRoman (CR=newline) | `MACROMAN`
EBCDIC | `EBCDIC`
DOS code page 437 | `CP437`
DOS code page 850 | `CP850`
DOS code page 858 | `CP858`
Windows code page 1250 | `CP1250`
Windows code page 1251 | `CP1251`
Windows code page 1252 | `CP1252`
Windows code page 1253 | `CP1253`
Windows code page 1254 | `CP1254`
Windows code page 1255 | `CP1255`
Windows code page 1256 | `CP1256`
Windows code page 1257 | `CP1257`
Windows code page 1258 | `CP1258`
KOI8-R | `KOI8-R`
KOI8-U | `KOI8-U`
KOI8-RU | `KOI8-RU`
Note that regex patterns are always specified in UTF-8 (includes ASCII). To
search binary files with binary patterns, see
[searching and displaying binary files with -U, -W, and -X](#binary).
To recursively list all files that are ASCII (i.e. 7-bit):
ug -RL '[^[:ascii:]]'
To recursively list all files that are non-ASCII, i.e. UTF-8, UTF-16, and
UTF-32 files with non-ASCII Unicode characters (U+0080 and up):
ug -Rl '[^[:ascii:]]'
To check if a file contains non-ASCII Unicode (U+0080 and up):
ug -q '[^[:ascii:]]' myfile && echo "contains Unicode"
To remove invalid Unicode characters from a file (note that `-o` does not work
because binary data is detected and rejected and newlines are added, but
`--format="%o%` does not check for binary and copies the match "as is"):
ug "\p{Unicode}" --format="%o" badfile.txt
To recursively list files with invalid UTF content (i.e. invalid UTF-8 byte
sequences or files that contain any UTF-8/16/32 code points that are outside
the valid Unicode range) by matching any code point with `.` and by using a
negative pattern `-N '\p{Unicode}'`:
ug -Rl -e '.' -N '\p{Unicode}'
To display lines containing laughing face emojis:
ug '[😀-😏]' emojis.txt
The same results are obtained using `\x{hhhh}` to select a Unicode character
range:
ug '[\x{1F600}-\x{1F60F}]' emojis.txt
To display lines containing the names Gödel (or Goedel), Escher, or Bach:
ug 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt
To search for `lorem` in lower or upper case in a UTF-16 file that is marked
with a UTF-16 BOM:
ug -iw 'lorem' utf16lorem.txt
To search utf16lorem.txt when this file has no UTF-16 BOM, using `--encoding`:
ug --encoding=UTF-16 -iw 'lorem' utf16lorem.txt
To search file `spanish-iso.txt` encoded in ISO-8859-1:
ug --encoding=ISO-8859-1 -w 'año' spanish-iso.txt
🔝 [Back to table of contents](#toc)
<a name="multiline"/>
### Matching multiple lines of text
-o, --only-matching
Output only the matching part of lines. Output additional matches
on the same line with `+' as the field separator. When multiple
lines match a pattern, output the matching lines with `|' as the
field separator. If -A, -B or -C is specified, fits the match and
its context on a line within the specified number of columns.
Multiple lines may be matched by patterns that match newline characters. Use
option `-o` to output the match only, not the full lines(s) that match.
To match a `\n` line break, include `\n` in the pattern to match the LF
character. If you want to match `\r\n` and `\n` line breaks, use `\r?\n` or
simply use `\R` to match any Unicode line break `\r\n`, `\r`, `\v`, `\f`, `\n`,
U+0085, U+2028 and U+2029.
To match C/C++ `/*...*/` multi-line comments:
ug '/\*([^*]|\n|(\*+([^*/]|\n)))*\*+\/' myfile.cpp
To match C/C++ comments using the predefined `c/comments` patterns with
`-f c/comments`, restricted to the matching part only with option `-o`:
ug -of c/comments myfile.cpp
Same as `sed -n '/begin/,/end/p'`: to match all lines between a line containing
`begin` and the first line after that containing `end`, using lazy repetition:
ug -o '.*begin(.|\n)*?end.*' myfile.txt
🔝 [Back to table of contents](#toc)
<a name="context"/>
### Displaying match context with -A, -B, -C, -y, and --width
-A NUM, --after-context=NUM
Output NUM lines of trailing context after matching lines. Places
a --group-separator between contiguous groups of matches. If -o is
specified, output the match with context to fit NUM columns after
the match or shortens the match. See also options -B, -C and -y.
-B NUM, --before-context=NUM
Output NUM lines of leading context before matching lines. Places
a --group-separator between contiguous groups of matches. If -o is
specified, output the match with context to fit NUM columns before
the match or shortens the match. See also options -A, -C and -y.
-C NUM, --context=NUM
Output NUM lines of leading and trailing context surrounding each
matching line. Places a --group-separator between contiguous
groups of matches. If -o is specified, output the match with
context to fit NUM columns before and after the match or shortens
the match. See also options -A, -B and -y.
-y, --any-line
Any line is output (passthru). Non-matching lines are output as
context with a `-' separator. See also options -A, -B, and -C.
--width[=NUM]
Truncate the output to NUM visible characters per line. The width
of the terminal window is used if NUM is not specified. Note that
double wide characters in the output may result in wider lines.
-o, --only-matching
Output only the matching part of lines. Output additional matches
on the same line with `+' as the field separator. When multiple
lines match a pattern, output the matching lines with `|' as the
field separator. If -A, -B or -C is specified, fits the match and
its context on a line within the specified number of columns.
To display two lines of context before and after a matching line:
ug -C2 'FIXME' myfile.cpp
To show three lines of context after a matched line:
ug -A3 'FIXME.*' myfile.cpp:
To display one line of context before each matching line with a C function
definition (C names are non-Unicode):
ug -B1 -f c/functions myfile.c
To display one line of context before each matching line with a C++ function
definition (C++ names may be Unicode):
ug -B1 -f c++/functions myfile.cpp
To display any non-matching lines as context for matching lines with `-y`:
ug -y -f c++/functions myfile.cpp
To display a hexdump of a matching line with one line of hexdump context:
ug -C1 -UX '\xaa\xbb\xcc' a.out
Context within a line is displayed with option `-o` with a context option:
ug -o -C20 'pattern' myfile.cpp
Same, but with pretty output with headings, line numbers and column numbers
(`-k`) and showing context:
ug --pretty -oC20 'pattern' myfile.cpp
🔝 [Back to table of contents](#toc)
<a name="source"/>
### Searching source code using -f, -g, -O, and -t
-f FILE, --file=FILE
Read newline-separated patterns from FILE. White space in patterns
is significant. Empty lines in FILE are ignored. If FILE does not
exist, the GREP_PATH environment variable is used as path to FILE.
If that fails, looks for FILE in /usr/local/share/ugrep/pattern.
When FILE is a `-', standard input is read. This option may be
repeated.
--ignore-files[=FILE]
Ignore files and directories matching the globs in each FILE that
is encountered in recursive searches. The default FILE is
`.gitignore'. Matching files and directories located in the
directory of a FILE's location and in directories below are ignored
by temporarily extending the --exclude and --exclude-dir globs, as
if --exclude-from=FILE is locally enforced. Globbing syntax is the
same as the --exclude-from=FILE gitignore syntax; directories are
excluded when the glob ends in a `/', same as git. Files and
directories explicitly specified as command line arguments are
never ignored. This option may be repeated with additional files.
-g GLOBS, --glob=GLOBS
Search only files whose name matches the specified comma-separated
list of GLOBS, same as --include='glob' for each `glob' in GLOBS.
When a `glob' is preceded by a `!' or a `^', skip files whose name
matches `glob', same as --exclude='glob'. When `glob' contains a
`/', full pathnames are matched. Otherwise basenames are matched.
When `glob' ends with a `/', directories are matched, same as
--include-dir='glob' and --exclude-dir='glob'. A leading `/'
matches the working directory. This option may be repeated and may
be combined with options -M, -O and -t to expand searches. See
`ugrep --help globs' and `man ugrep' section GLOBBING for details.
-O EXTENSIONS, --file-extension=EXTENSIONS
Search only files whose filename extensions match the specified
comma-separated list of EXTENSIONS, same as --include='*.ext' for
each `ext' in EXTENSIONS. When `ext' is preceded by a `!' or a
`^', skip files whose filename extensions matches `ext', same as
--exclude='*.ext'. This option may be repeated and may be combined
with options -g, -M and -t to expand the recursive search.
-t TYPES, --file-type=TYPES
Search only files associated with TYPES, a comma-separated list of
file types. Each file type corresponds to a set of filename
extensions passed to option -O and filenames passed to option -g.
For capitalized file types, the search is expanded to include files
with matching file signature magic bytes, as if passed to option
-M. When a type is preceded by a `!' or a `^', excludes files of
the specified type. This option may be repeated.
--stats
Output statistics on the number of files and directories searched,
and the inclusion and exclusion constraints applied.
The file types are listed with `ugrep -tlist`. The list is based on
established filename extensions and "magic bytes". If you have a file type
that is not listed, use options `-O` and/or `-M`. You may want to define an
alias, e.g. `alias ugft='ugrep -Oft'` as a shorthand to search files with
filename suffix `.ft`.
To recursively display function definitions in C/C++ files (`.h`, `.hpp`, `.c`,
`.cpp` etc.) with line numbers with `-tc++`, `-o`, `-n`, and `-f c++/functions`:
ug -on -tc++ -f c++/functions
To recursively display function definitions in `.c` and `.cpp` files with line
numbers with `-Oc,cpp`, `-o`, `-n`, and `-f c++/functions`:
ug -on -Oc,cpp -f c++/functions
To recursively list all shell files with `-tShell` to match filename extensions
and files with shell shebangs, except files with suffix `.sh`:
ug -l -tShell -O^sh ''
To recursively list all non-shell files with `-t^Shell`:
ug -l -t^Shell ''
To recursively list all shell files with shell shebangs that have no shell
filename extensions:
ug -l -tShell -t^shell ''
To search for lines with `FIXME` in C/C++ comments, excluding `FIXME` in
multi-line strings:
ug -n 'FIXME' -f c++/zap_strings myfile.cpp
To read patterns `TODO` and `FIXME` from standard input to match lines in the
input, while excluding matches in C++ strings:
ug -on -f - -f c++/zap_strings myfile.cpp <<END
TODO
FIXME
END
To display XML element and attribute tags in an XML file, restricted to the
matching part with `-o`, excluding tags that are placed in (multi-line)
comments:
ug -o -f xml/tags -f xml/zap_comments myfile.xml
🔝 [Back to table of contents](#toc)
<a name="archives"/>
### Searching compressed files and archives with -z
-z, --decompress
Decompress files to search, when compressed. Archives (.cpio,
.pax, .tar and .zip) and compressed archives (e.g. .taz, .tgz,
.tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, .txz, .tzst) are searched and
matching pathnames of files in archives are output in braces. If
-g, -O, -M, or -t is specified, searches files stored in archives
whose filenames match globs, match filename extensions, match file
signature magic bytes, or match file types, respectively.
Supported compression formats: gzip (.gz), compress (.Z), zip,
bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
lzma and xz (requires suffix .lzma, .tlz, .xz, .txz),
lz4 (requires suffix .lz4),
zstd (requires suffix .zst, .zstd, .tzst).
--zmax=NUM
When used with option -z (--decompress), searches the contents of
compressed files and archives stored within archives by up to NUM
recursive expansions. The default --zmax=1 only permits searching
uncompressed files stored in cpio, pax, tar and zip archives;
compressed files and archives are detected as binary files and are
effectively ignored. Specify --zmax=2 to search compressed files
and archives stored in cpio, pax, tar and zip archives. NUM may
range from 1 to 99 for up to 99 decompression and de-archiving
steps. Increasing NUM values gradually degrades performance.
Files compressed with gzip (`.gz`), compress (`.Z`), bzip2 (`.bz`, `.bz2`,
`.bzip2`), lzma (`.lzma`), xz (`.xz`), lz4 (`.lz4`) and zstd (`.zst`, `.zstd`)
are searched with option `-z`. This option does not require files to be
compressed. Uncompressed files are searched also.
Other compression formats can be searched with **ugrep** [filters](#filter).
Archives (cpio, jar, pax, tar, and zip) are searched with option `-z`. Regular
files in an archive that match are output with the archive pathnames enclosed
in `{` and `}` braces. Supported tar formats are v7, ustar, gnu, oldgnu, and
pax. Supported cpio formats are odc, newc, and crc. Not supported is the
obsolete non-portable old binary cpio format. Archive formats cpio, tar, and
pax are automatically recognized with option `-z` based on their content,
independent of their filename suffix.
By default, uncompressed archives stored within zip archives are also searched:
all cpio, pax, and tar files in zip archives are automatically recognized and
searched. However, by default compressed files stored within archives are not
recognized, e.g. zip files stored within tar files are not searched but rather
all compressed files and archives are searched as if they are binary files
without decompressing them.
Specify `--zmax=NUM` to search archives that contain compressed files and
archives for up to `NUM` levels deep. The value of `NUM` may range from 1 to
99 for up to 99 decompression and de-archiving steps to expand up to 99 nested
archives. Larger `--zmax=NUM` values degrade performance. It is unlikely you
will ever need 99 as `--zmax=2` suffices for most practical use cases, such as
searching zip files stored in tar files.
When option `-z` is used with options `-g`, `-O`, `-M`, or `-t`, archives and
compressed and uncompressed files that match the filename selection criteria
(glob, extension, magic bytes, or file type) are searched only. For example,
`ugrep -r -z -tc++` searches C++ files such as `main.cpp` and zip and tar
archives that contain C++ files such as `main.cpp`. Also included in the
search are compressed C++ files such as `main.cpp.gz` and `main.cpp.xz` when
present. Also any cpio, pax, tar, and zip archives when present are searched
for C++ files that they contain, such as `main.cpp`. Use option `--stats` to
see a list of the glob patterns applied to filter file pathnames in the
recursive search and when searching archive contents.
When option `-z` is used with options `-g`, `-O`, `-M`, or `-t` to search cpio,
jar, pax, tar, and zip archives, archived files that match the filename selection
criteria are searched only.
The gzip, compress, and zip formats are automatically detected, which is useful
when reading gzip-compressed data from standard input, e.g. input redirected
from a pipe. Other compression formats require a filename suffix: `.bz`,
`.bz2`, or `.bzip2` for bzip2, `.lzma` for lzma, `.xz` for xz, `.lz4` for lz4
and `.zst` or `.zstd` for zstd. Also the compressed tar archive shorthands
`.taz`, `.tgz` and `.tpz` for gzip, `.tbz`, `.tbz2`, `.tb2`, and `.tz2` for
bzip2, `.tlz` for lzma, `.txz` for xz, and `.tzst` for zstd are recognized. To
search these formats with ugrep from standard input, use option
`--label='stdin.bz2'` for bzip2, `--label='stdin.lzma'` for lzma,
`--label='stdin.xz'` for xz, `--label='stdin.lz4` for lz4 and
`--label='stdin.zst` for zstd. The name `stdin` is arbitrary and may be
omitted:
format | filename suffix | tar/pax archive short suffix | suffix required? | ugrep from stdin | lib required |
--------- | ----------------------- | ------------------------------- | ---------------- | ---------------- | ------------ |
gzip | `.gz` | `.taz`, `.tgz`, `.tpz` | no | automatic | libz |
compress | `.Z` | `.taZ`, `.tZ` | no | automatic | *built-in* |
zip | `.zip`, `.zipx`, `.ZIP` | | no | automatic | libz |
bzip2 | `.bz`, `.bz2`, `.bzip2` | `.tb2`, `.tbz`, `.tbz2`, `.tz2` | yes | `--label=.bz2` | libbz2 |
lzma | `.lzma` | `.tlz` | yes | `--label=.lzma` | liblzma |
xz | `.xz` | `.txz` | yes | `--label=.xz` | liblzma |
lz4 | `.lz4` | | yes | `--label=.lz4` | liblz4 |
zstd | `.zst`, `.zstd` | `.tzst` | yes | `--label=.zst` | libzstd |
The gzip, bzip2, xz, lz4 and zstd formats support concatenated compressed
files. Concatenated compressed files are searched as one file.
Supported zip compression methods are stored (0), deflate (8), bzip2 (12), lzma
(14), xz (95) and zstd (93). The bzip2, lzma, xz and zstd methods require
ugrep to be compiled with the corresponding compression libraries.
Searching encrypted zip archives is not supported (perhaps in future releases,
depending on requests for enhancements).
Option `-z` uses threads for task parallelism to speed up searching larger
files by running the decompressor concurrently with a search of the
decompressed stream.
To list all non-empty files stored in a `package.zip` archive, including the
contents of all cpio, pax, tar and zip files that are stored in it:
ug --zmax=2 -z -l '' package.zip
Same, but only list the Python source code files, including scripts that invoke
Python, with option `-tPython` (`ugrep -tlist` for details):
ug --zmax=2 -z -l -tPython '' package.zip
To search Python applications distributed as a tar file with their dependencies
includes as wheels (zip files with Python code), searching for the word
`my_class` in `app.tgz`:
ug --zmax=2 -z -tPython -w my_class app.tgz
To recursively search C++ files including compressed files for the word
`my_function`, while skipping C and C++ comments:
ug -z -r -tc++ -Fw my_function -f cpp/zap_comments
To search bzip2, lzma, xz, lz4 and zstd compressed data on standard input,
option `--label` may be used to specify the extension corresponding to the
compression format to force decompression when the bzip2 extension is not
available to ugrep, for example:
cat myfile.bz2 | ugrep -z --label='stdin.bz2' 'xyz'
To search file `main.cpp` in `project.zip` for `TODO` and `FIXME` lines:
ug -z -g main.cpp -w -e 'TODO' -e 'FIXME' project.zip
To search tarball `project.tar.gz` for C++ files with `TODO` and `FIXME` lines:
ug -z -tc++ -w -e 'TODO' -e 'FIXME' project.tar.gz
To search files matching the glob `*.txt` in `project.zip` for the word
`license` in any case (note that the `-g` glob argument must be quoted):
ug -z -g '*.txt' -w -i 'license' project.zip
To display and page through all C++ files in tarball `project.tgz`:
ug --pager -z -tc++ '' project.tgz
To list the files matching the gitignore-style glob `/**/projects/project1.*`
in `projects.tgz`, by selecting files containing in the archive the text
`December 12`:
ug -z -l -g '/**/projects/project1.*' -F 'December 12' projects.tgz
To view the META-INF/MANIFEST.MF data in a jar file with `-Ojar` and `-OMF` to
select the jar file and the MF file therein (`-Ojar` is required, otherwise the
jar file will be skipped though we could read it from standard input instead):
ug -z -h -OMF,jar '' my.jar
To extract C++ files that contain `FIXME` from `project.tgz`, we use `-m1`
with `--format="'%z '"` to generate a space-separated list of pathnames of file
located in the archive that match the word `FIXME`:
tar xzf project.tgz `ugrep -z -l -tc++ --format='%z ' -w FIXME project.tgz`
To perform a depth-first search with `find`, then use `cpio` and `ugrep` to
search the files:
find . -depth -print | cpio -o | ugrep -z 'xyz'
🔝 [Back to table of contents](#toc)
<a name="magic"/>
### Find files by file signature and shebang "magic bytes" with -M, -O and -t
--ignore-files[=FILE]
Ignore files and directories matching the globs in each FILE that
is encountered in recursive searches. The default FILE is
`.gitignore'. Matching files and directories located in the
directory of a FILE's location and in directories below are ignored
by temporarily extending the --exclude and --exclude-dir globs, as
if --exclude-from=FILE is locally enforced. Globbing syntax is the
same as the --exclude-from=FILE gitignore syntax; directories are
excluded when the glob ends in a `/', same as git. Files and
directories explicitly specified as command line arguments are
never ignored. This option may be repeated with additional files.
-M MAGIC, --file-magic=MAGIC
Only files matching the signature pattern MAGIC are searched. The
signature \"magic bytes\" at the start of a file are compared to
the MAGIC regex pattern. When matching, the file will be searched.
When MAGIC is preceded by a `!' or a `^', skip files with matching
MAGIC signatures. This option may be repeated and may be combined
with options -O and -t to expand the search. Every file on the
search path is read, making searches potentially more expensive.
-O EXTENSIONS, --file-extension=EXTENSIONS
Search only files whose filename extensions match the specified
comma-separated list of EXTENSIONS, same as --include='*.ext' for
each `ext' in EXTENSIONS. When `ext' is preceded by a `!' or a
`^', skip files whose filename extensions matches `ext', same as
--exclude='*.ext'. This option may be repeated and may be combined
with options -g, -M and -t to expand the recursive search.
-t TYPES, --file-type=TYPES
Search only files associated with TYPES, a comma-separated list of
file types. Each file type corresponds to a set of filename
extensions passed to option -O and filenames passed to option -g.
For capitalized file types, the search is expanded to include files
with matching file signature magic bytes, as if passed to option
-M. When a type is preceded by a `!' or a `^', excludes files of
the specified type. This option may be repeated.
-g GLOBS, --glob=GLOBS
Search only files whose name matches the specified comma-separated
list of GLOBS, same as --include='glob' for each `glob' in GLOBS.
When a `glob' is preceded by a `!' or a `^', skip files whose name
matches `glob', same as --exclude='glob'. When `glob' contains a
`/', full pathnames are matched. Otherwise basenames are matched.
When `glob' ends with a `/', directories are matched, same as
--include-dir='glob' and --exclude-dir='glob'. A leading `/'
matches the working directory. This option may be repeated and may
be combined with options -M, -O and -t to expand searches. See
`ugrep --help globs' and `man ugrep' section GLOBBING for details.
--stats
Output statistics on the number of files and directories searched,
and the inclusion and exclusion constraints applied.
To recursively list all files that start with `#!` shebangs:
ug -l -M'#!' ''
To recursively list all files that start with `#` but not with `#!` shebangs:
ug -l -M'#' -M'^#!' ''
To recursively list all Python files (extension `.py` or a shebang) with
`-tPython`:
ug -l -tPython ''
To recursively list all non-shell files with `-t^Shell`:
ug -l -t^Shell ''
To recursively list Python files (extension `.py` or a shebang) that have
import statements, including hidden files with `-.`:
ug -l. -tPython -f python/imports
🔝 [Back to table of contents](#toc)
<a name="fuzzy"/>
### Fuzzy search with -Z
-Z[best][+-~][MAX], --fuzzy=[best][+-~][MAX]
Fuzzy mode: report approximate pattern matches within MAX errors.
The default is -Z1: one deletion, insertion or substitution is
allowed. If `+`, `-' and/or `~' is specified, then `+' allows
insertions, `-' allows deletions and `~' allows substitutions. For
example, -Z+~3 allows up to three insertions or substitutions, but
no deletions. If `best' is specified, then only the best matching
lines are output with the lowest cost per file. Option -Zbest
requires two passes over a file and cannot be used with standard
input or Boolean queries. Option --sort=best orders matching files
by best match. The first character of an approximate match always
matches a character at the beginning of the pattern. To fuzzy
match the first character, replace it with a `.' or `.?'. Option
-U applies fuzzy matching to ASCII and bytes instead of Unicode
text. No whitespace may be given between -Z and its argument.
The beginning of a pattern always matches the first character of an approximate
match as a practical strategy to prevent many false "randomized" matches for
short patterns. This also greatly improves search speed. Make the first
character optional to optionally match it, e.g. `p?attern` or use a dot as
the start of the pattern to match any wide character (but this is slow).
Line feed (`\n`) and NUL (`\0`) characters are never deleted or substituted to
ensure that fuzzy matches do not extend the pattern match beyond the number of
lines specified by the regex pattern.
Option `-U` (`--binary`) restricts fuzzy matches to ASCII and binary only with
edit distances measured in bytes. Otherwise, fuzzy pattern matching is
performed with Unicode patterns and edit distances are measured in Unicode
characters.
Option `--sort=best` orders files by best match. Files with at least one exact
match anywhere in the file are shown first, followed by files with approximate
matches in increasing minimal edit distance order. That is, ordered by the
minimum error (edit distance) found among all approximate matches per file.
To recursively search for approximate matches of the word `foobar` with `-Z`,
i.e. approximate matching with one error, e.g. `Foobar`, `foo_bar`, `foo bar`,
`fobar`:
ug -Z 'foobar'
Same, but matching words only with `-w` and ignoring case with `-i`:
ug -Z -wi 'foobar'
Same, but permit up to 2 insertions with `-Z+2`, no deletions/substitutions
(matches up to 2 extra characters, such as `foos bar`), insertions-only offers
the fastest fuzzy matching method:
ug -Z+3 -wi 'foobar'
Same, but sort matches from best (at least one exact match or fewest fuzzy
match errors) to worst:
ug -Z+3 -wi --sort=best 'foobar'
**Note:** because sorting by best match requires two passes over the input
files, the efficiency of concurrent searching is significantly reduced.
Same, but with customized formatting to show the edit distance "cost" of the
approximate matches with format field `%Z` and `%F` to show the pathname:
ug -Z+3 -wi --format='%F%Z:%O%~' --sort=best 'foobar'
Same, but this time count the matches with option `-c` and display them with a
custom format using `%m`, where `%Z` is the *average* cost per match:
ug -c -Z+3 -wi --format='%F%Z:%m%~' --sort=best 'foobar'
**Note:** options `-c` and `-l` do not report a meaningful `%Z` value in the
`--format` output, because `%Z` is the edit distance cost of a single match.
🔝 [Back to table of contents](#toc)
<a name="hidden">
### Search hidden files with -.
--hidden, -.
Search hidden files and directories.
To recursively search the working directory, including hidden files and
directories, for the word `login` in shell scripts:
ug -. -tShell 'login'
🔝 [Back to table of contents](#toc)
<a name="filter"/>
### Using filter utilities to search documents with --filter
--filter=COMMANDS
Filter files through the specified COMMANDS first before searching.
COMMANDS is a comma-separated list of `exts:command [option ...]',
where `exts' is a comma-separated list of filename extensions and
`command' is a filter utility. The filter utility should read from
standard input and write to standard output. Files matching one of
`exts' are filtered. When `exts' is `*', files with non-matching
extensions are filtered. One or more `option' separated by spacing
may be specified, which are passed verbatim to the command. A `%'
as `option' expands into the pathname to search. For example,
--filter='pdf:pdftotext % -' searches PDF files. The `%' expands
into a `-' when searching standard input. Option --label=.ext may
be used to specify extension `ext' when searching standard input.
--filter-magic-label=LABEL:MAGIC
Associate LABEL with files whose signature "magic bytes" match the
MAGIC regex pattern. Only files that have no filename extension
are labeled, unless +LABEL is specified. When LABEL matches an
extension specified in --filter=COMMANDS, the corresponding command
is invoked. This option may be repeated.
The `--filter` option associates one or more filter utilities with specific
filename extensions. A filter utility is selected based on the filename
extension and executed by forking a process: the utility's standard input
reads the open input file and the utility's standard output is searched. When
a `%` is specified as an option to the utility, the `%` is expanded to the
pathname of the file to open and read by the utility.
When a specified utility is not found on the system, an error message is
displayed. When a utility fails to produce output, e.g. when the specified
options for the utility are invalid, the search is silently skipped.
Common filter utilities are `cat` (concat, pass through), `head` (select first
lines or bytes) `tr` (translate), `iconv` and `uconv` (convert), and more
advanced utilities such as:
- [`pdftotext`](https://pypi.org/project/pdftotext) to convert PDF to text
- [`pandoc`](https://pandoc.org) to convert .docx, .epub, and other document
formats
- [`soffice`](https://www.libreoffice.org) to convert office documents
- [`csvkit`](https://pypi.org/project/csvkit) to convert spreadsheets
- [`openssl`](https://wiki.openssl.org/index.php/Command_Line_Utilities) to
convert certificates and key files to text and other formats
- [`exiftool`](http://exiftool.sourceforge.net) to read meta information
embedded in image and video media formats.
Also decompressors may be used as filter utilities, such as `unzip`, `gunzip`,
`bunzip2`, `unlzma`, `unxz`, `lzop` and `7z` that decompress files to standard
output when option `--stdout` is specified. For example:
ug --filter='lzo:lzop -d --stdout -' ...
ug --filter='gz:gunzip -d --stdout -' ...
ug --filter='7z:7z x -so %' ...
The `--filter='lzo:lzop -d --stdout -' option decompresses files with extension
`lzo` to standard output with `--stdout` with the compressed stream being read
from standard input with `-`. The `--filter='7z:7z x -so -si` option
decompresses files with extension `7z` to standard output `-so` while reading
standard input `-si` with the compressed file contents.
Note that **ugrep** option `-z` is typically faster to search compressed files
compared to `--filter`.
The `--filter` option may also be used to run a user-defined shell script to
filter files. For example, to invoke an action depending on the filename
extension of the `%` argument. Another use case is to pass a file to more than
one filter, which can be accomplished with a shell script containing the line
`tool1 $1; tool2 $1`. This filters the file argument `$1` with `tool1`
followed by `tool2` to produce combined output to search for pattern matches.
Likewise, we can use a script with the line `tool1 $1 | tool2` to stack two
filters `tool1` and `tool2`.
The `--filter` option may also be used as a predicate to skip certain files
from the search. As the most basic example, consider the `false` utility that
exits with a nonzero exit code without reading input or producing output.
Therefore, `--filter='swp: false'` skips all `.swp` files from recursive
searches. The same can be done more efficiently with `-O^swp`. However,
the `--filter` option could invoke a script that determines if the filename
passed as a `%` argument meets certain constraints. If the constraint is met
the script copies standard input to standard output with `cat`. If not, the
script exits.
**Warning:** option `--filter` should not be used with utilities that modify
files. Otherwise searches may be unpredicatable. In the worst case files may
be lost, for example when the specified utility replaces or deletes the file
passed to the command with `--filter` option `%`.
To recursively search files including PDF files in the working directory
without recursing into subdirectories (with `-1`), for matches of `drink me`
using the `pdftotext` filter to convert PDF to text without preserving page
breaks:
ug -r -1 --filter='pdf:pdftotext -nopgbrk % -' 'drink me'
To recursively search text files for `eat me` while converting non-printable
characters in .txt and .md files using the `cat -v` filter:
ug -r -ttext --filter='txt,md:cat -v' 'eat me'
The same, but specifying the .txt and .md filters separately:
ug -r -ttext --filter='txt:cat -v, md:cat -v' 'eat me'
To search the first 8K of a text file:
ug --filter='txt:head -c 8192' 'eat me' wonderland.txt
To recursively search and list the files that contain the word `Alice`,
including .docx and .epub documents using the `pandoc` filter:
ug -rl -w --filter='docx,epub:pandoc --wrap=preserve -t markdown % -o -' 'Alice'
**Important:** the `pandoc` utility requires an input file and will not read
standard input. Option `%` expands into the full pathname of the file to
search. The output format specified is `markdown`, which is close enough to
text to be searched.
To recursively search and list the files that contain the word `Alice`,
including .odt, .doc, .docx, .rtf, .xls, .xlsx, .ppt, .pptx documents using the
`soffice` filter:
ug -rl -w --filter='odt,doc,docx,rtf,xls,xlsx,ppt,pptx:soffice --headless --cat %' 'Alice'
**Important:** the `soffice` utility will not output any text when one or more
LibreOffice GUIs are open. Make sure to quit all LibreOffice apps first. This
looks like a bug, but the LibreOffice developers do not appear to fix this
any time soon (unless perhaps more people complain.)
To recursively search and display rows of .csv, .xls, and .xlsx spreadsheets
that contain `10/6` using the `in2csv` filter of csvkit:
ug -r -Ocsv,xls,xlsx --filter='xls,xlsx:in2csv %' '10/6'
To search .docx, .xlsx, and .pptx files converted to XML for a match with
`10/6` using `unzip` as a filter:
ug -lr -Odocx,xlsx,pptx --filter='docx,xlsx,pptx:unzip -p %' '10/6'
**Important:** unzipping docx, xlxs, pptx files produces extensive XML output
containing meta information and binary data such as images. By contrast,
**ugrep** option `-z` with `-Oxml` selects the XML components only:
ug -z -lr -Odocx,xlsx,pptx,xml '10/6'
**Note:** docx, xlsx, and pptx are zip files containing multiple components.
When selecting the XML components with option `-Oxml` in docx, xlsx, and pptx
documents, we should also specify `-Odocx,xlsx,pptx` to search these type of
files, otherwise these files will be ignored.
To recurssively search X509 certificate files for lines with `Not After` (e.g.
to find expired certificates), using `openssl` as a filter:
ug -r 'Not After' -Ocer,der,pem --filter='pem:openssl x509 -text,cer,crt,der:openssl x509 -text -inform der'
Note that `openssl` warning messages are displayed on standard error. If
a file cannot be converted it is probably in a different format. This can
be resolved by writing a shell script that executes `openssl` with options
based on the file content. Then write a script with `ugrep --filter`.
To search PNG files by filename extension with `-tpng` using `exiftool`:
ug -r -i 'copyright' -tpng --filter='*:exiftool %'
Same, but also include files matching PNG "magic bytes" with `-tPng` and
`--filter-magic-label='+png:\x89png\x0d\x0a\x1a\x0a'` to select the `png`
filter:
ug -r -i 'copyright' -tPng --filter='png:exiftool %' --filter-magic-label='+png:\x89png\x0d\x0a\x1a\x0a'
Note that `+png` overrides any filename extension match for `--filter`.
Otherwise, without a `+`, the filename extension, when present, takes priority
over labelled magic patterns to invoke the corresponding filter command.
The `LABEL` used with `--filter-magic-label` and `--filter` has no specific
meaning; any name or string that does not contain a `:` or `,` may be used.
🔝 [Back to table of contents](#toc)
<a name="binary"/>
### Searching and displaying binary files with -U, -W, and -X
-U, --binary
Disables Unicode matching for binary file matching, forcing PATTERN
to match bytes, not Unicode characters. For example, -U '\xa3'
matches byte A3 (hex) instead of the Unicode code point U+00A3
represented by the UTF-8 sequence C2 A3. See also --dotall.
-W, --with-hex
Output binary matches in hexadecimal, leaving text matches alone.
This option is equivalent to the --binary-files=with-hex option
with --hexdump=2C. To omit the matching line from the hex output,
combine option --hexdump with option -W. See also option -U.
-X, --hex
Output matches in hexadecimal. This option is equivalent to the
--binary-files=hex option with --hexdump=2C. To omit the matching
line from the hex output, use option --hexdump instead of -X. See
also option -U.
--hexdump=[1-8][a][bch][A[NUM]][B[NUM]][C[NUM]]
Output matches in 1 to 8 columns of 8 hexadecimal octets. The
default is 2 columns or 16 octets per line. Option `a' outputs a
`*' for all hex lines that are identical to the previous hex line,
`b' removes all space breaks, `c' removes the character column, `h'
removes hex spacing, `A' includes up to NUM hex lines after the
match, `B' includes up to NUM hex lines before the match and `C'
includes up to NUM hex lines. When NUM is omitted, the matching
line is included in the output. See also options -U, -W and -X.
--dotall
Dot `.' in regular expressions matches anything, including newline.
Note that `.*' matches all input and should not be used.
Note that `--hexdump` differs from `-X` by omitting the matching line from the
hex output, showing only the matching pattern using a minimal number of hex
lines. Option `-X` is the same as `--hexdump=2C` to display the matching line
as hex `C` context.
To search a file for ASCII words, displaying text lines as usual while binary
content is shown in hex with `-U` and `-W`:
ug -UW '\w+' myfile
To hexdump an entire file as a match with `-X`:
ug -X '' myfile
To hexdump an entire file with `-X`, displaying line numbers and byte offsets
with `-nb` (here with `-y` to display all line numbers):
ug -Xynb '' myfile
To hexdump lines containing one or more \0 in a (binary) file using a
non-Unicode pattern with `-U` and `-X`:
ug -UX '\x00+' myfile
Same, but hexdump the entire file as context with `-y` (note that this
line-based option does not permit matching patterns with newlines):
ug -UX -y '\x00+' myfile
Same, compacted to 32 bytes per line without the character column:
ug -UX -y '\x00+' myfile
To match the binary pattern `A3..A3.` (hex) in a binary file without
Unicode pattern matching (which would otherwise match `\xaf` as a Unicode
character U+00A3 with UTF-8 byte sequence C2 A3) and display the results
in compact hex with `--hexdump` with pager `less -R`:
ug --pager --hexdump -U '\xa3[\x00-\xff]{2}\xa3[\x00-\xff]' a.out
Same, but using option `--dotall` to let `.` match any byte, including
newline that is not matched by dot (the default as required by grep):
ug --dotall --pager --hexdump -U '\xa3.{2}\xa3.' a.out
To list all files containing a RPM signature, located in the `rpm` directory and
recursively below (see for example
[list of file signatures](https://en.wikipedia.org/wiki/List_of_file_signatures)):
ug -RlU '\A\xed\xab\xee\xdb' rpm
🔝 [Back to table of contents](#toc)
<a name="nobinary">
### Ignore binary files with -I
-I Ignore matches in binary files. This option is equivalent to the
--binary-files=without-match option.
To recursively search without following symlinks and ignoring binary files:
ug -rl -I 'xyz'
To ignore specific binary files with extensions such as .exe, .bin, .out, .a,
use `--exclude` or `--exclude-from`:
ug -rl --exclude-from=ignore_binaries 'xyz'
where `ignore_binaries` is a file containing a glob on each line to ignore
matching files, e.g. `*.exe`, `*.bin`, `*.out`, `*.a`. Because the command is
quite long to type, an alias for this is recommended, for example `ugs` (ugrep
source):
alias ugs="ugrep --exclude-from=~/ignore_binaries"
ugs -rl 'xyz'
🔝 [Back to table of contents](#toc)
<a name="ignore"/>
### Ignoring .gitignore-specified files with --ignore-files
--ignore-files[=FILE]
Ignore files and directories matching the globs in each FILE that
is encountered in recursive searches. The default FILE is
`.gitignore'. Matching files and directories located in the
directory of a FILE's location and in directories below are ignored
by temporarily extending the --exclude and --exclude-dir globs, as
if --exclude-from=FILE is locally enforced. Globbing syntax is the
same as the --exclude-from=FILE gitignore syntax; directories are
excluded when the glob ends in a `/', same as git. Files and
directories explicitly specified as command line arguments are
never ignored. This option may be repeated with additional files.
Option `--ignore-files` looks for `.gitignore`, or the specified `FILE`, in
recursive searches. When `.gitignore`, or the specified `FILE`, is found while
traversing directory tree branches down, the `.gitignore` file is used to
temporarily extend the previous exclusions with the additional globs in
`.gitignore` to apply the combined exclusions to the directory tree rooted at
the `.gitignore` location. Use `--stats` to show the selection criteria
applied to the search results and the locations of each `FILE` found. To avoid
confusion, files and directories specified as command-line arguments to
**ugrep** are never ignored.
Note that exclude glob patterns take priority over include glob patterns when
specified with command line options. By contrast, negated glob patterns
specified with `!` in `--ignore-files` files take priority. This effectively
overrides the exclusions and resolves conflicts in favor of listing matching
files that are explicitly specified as exceptions and should be included in the
search.
See also [Using gitignore-style globs to select directories and files to search](#globs).
To recursively search without following symlinks, while ignoring files and
directories ignored by .gitignore (when present), use option `--ignore-files`.
Note that `-r` is the default when no FILE arguments are specified, we use it
here to make the examples easier to follow.
ug -rl --ignore-files 'xyz'
Same, but includes hidden files with `-.` rather than ignoring them:
ug -rl. --ignore-files 'xyz'
To recursively list all files that are not ignored by .gitignore (when present)
with `--ignore-files`:
ug -rl --ignore-files ''
Same, but list shell scripts that are not ignored by .gitignore, when present:
ug -rl -tShell '' --ignore-files
To recursively list all files that are not ignored by .gitignore and are also
not excluded by `.git/info/exclude`:
ug -rl '' --ignore-files --exclude-from=.git/info/exclude
Same, but by creating a symlink to `.git/info/exclude` to make the exclusions
implicit:
ln -s .git/info/exclude .ignore
ug -rl '' --ignore-files --ignore-files=.ignore
🔝 [Back to table of contents](#toc)
<a name="globs"/>
### Using gitignore-style globs to select directories and files to search
-g GLOBS, --glob=GLOBS
Search only files whose name matches the specified comma-separated
list of GLOBS, same as --include='glob' for each `glob' in GLOBS.
When a `glob' is preceded by a `!' or a `^', skip files whose name
matches `glob', same as --exclude='glob'. When `glob' contains a
`/', full pathnames are matched. Otherwise basenames are matched.
When `glob' ends with a `/', directories are matched, same as
--include-dir='glob' and --exclude-dir='glob'. A leading `/'
matches the working directory. This option may be repeated and may
be combined with options -M, -O and -t to expand searches. See
`ugrep --help globs' and `man ugrep' section GLOBBING for details.
--exclude=GLOB
Skip files whose name matches GLOB using wildcard matching, same as
-g ^GLOB. GLOB can use **, *, ?, and [...] as wildcards, and \\ to
quote a wildcard or backslash character literally. When GLOB
contains a `/', full pathnames are matched. Otherwise basenames
are matched. When GLOB ends with a `/', directories are excluded
as if --exclude-dir is specified. Otherwise files are excluded.
Note that --exclude patterns take priority over --include patterns.
GLOB should be quoted to prevent shell globbing. This option may
be repeated.
--exclude-dir=GLOB
Exclude directories whose name matches GLOB from recursive
searches, same as -g ^GLOB/. GLOB can use **, *, ?, and [...] as
wildcards, and \\ to quote a wildcard or backslash character
literally. When GLOB contains a `/', full pathnames are matched.
Otherwise basenames are matched. Note that --exclude-dir patterns
take priority over --include-dir patterns. GLOB should be quoted
to prevent shell globbing. This option may be repeated.
--exclude-from=FILE
Read the globs from FILE and skip files and directories whose name
matches one or more globs. A glob can use **, *, ?, and [...] as
wildcards, and \ to quote a wildcard or backslash character
literally. When a glob contains a `/', full pathnames are matched.
Otherwise basenames are matched. When a glob ends with a `/',
directories are excluded as if --exclude-dir is specified.
Otherwise files are excluded. A glob starting with a `!' overrides
previously-specified exclusions by including matching files. Lines
starting with a `#' and empty lines in FILE are ignored. When FILE
is a `-', standard input is read. This option may be repeated.
--ignore-files[=FILE]
Ignore files and directories matching the globs in each FILE that
is encountered in recursive searches. The default FILE is
`.gitignore'. Matching files and directories located in the
directory of a FILE's location and in directories below are ignored
by temporarily overriding the --exclude and --exclude-dir globs,
as if --exclude-from=FILE is locally enforced. Globbing is the
same as --exclude-from=FILE and supports gitignore syntax, but
directories are not automatically excluded from searches (use a
glob ending with a `/' to identify directories to ignore, same as
git). Files and directories explicitly specified as command line
arguments are never ignored. This option may be repeated.
--include=GLOB
Search only files whose name matches GLOB using wildcard matching,
same as -g GLOB. GLOB can use **, *, ?, and [...] as wildcards,
and \\ to quote a wildcard or backslash character literally. When
GLOB contains a `/', full pathnames are matched. Otherwise
basenames are matched. When GLOB ends with a `/', directories are
included as if --include-dir is specified. Otherwise files are
included. Note that --exclude patterns take priority over
--include patterns. GLOB should be quoted to prevent shell
globbing. This option may be repeated.
--include-dir=GLOB
Only directories whose name matches GLOB are included in recursive
searches, same as -g GLOB/. GLOB can use **, *, ?, and [...] as
wildcards, and \\ to quote a wildcard or backslash character
literally. When GLOB contains a `/', full pathnames are matched.
Otherwise basenames are matched. Note that --exclude-dir patterns
take priority over --include-dir patterns. GLOB should be quoted
to prevent shell globbing. This option may be repeated.
--include-from=FILE
Read the globs from FILE and search only files and directories
whose name matches one or more globs. A glob can use **, *, ?, and
[...] as wildcards, and \ to quote a wildcard or backslash
character literally. When a glob contains a `/', full pathnames
are matched. Otherwise basenames are matched. When a glob ends
with a `/', directories are included as if --include-dir is
specified. Otherwise files are included. A glob starting with a
`!' overrides previously-specified inclusions by excluding matching
files. Lines starting with a `#' and empty lines in FILE are
ignored. When FILE is a `-', standard input is read. This option
may be repeated.
-O EXTENSIONS, --file-extension=EXTENSIONS
Search only files whose filename extensions match the specified
comma-separated list of EXTENSIONS, same as --include='*.ext' for
each `ext' in EXTENSIONS. When `ext' is preceded by a `!' or a
`^', skip files whose filename extensions matches `ext', same as
--exclude='*.ext'. This option may be repeated and may be combined
with options -g, -M and -t to expand the recursive search.
--stats
Output statistics on the number of files and directories searched,
and the inclusion and exclusion constraints applied.
See also [Including or excluding mounted file systems from searches](#fs).
Gitignore-style glob syntax and conventions:
pattern | matches
---------- | ------------------------------------------------------------------
`*` | anything except `/`
`?` | any one character except `/`
`[abc-e]` | one character `a`,`b`,`c`,`d`,`e`
`[^abc-e]` | one character not `a`,`b`,`c`,`d`,`e`,`/`
`[!abc-e]` | one character not `a`,`b`,`c`,`d`,`e`,`/`
`/` | when used at the start of a glob, matches working directory
`**/` | zero or more directories
`/**` | when at the end of a glob, matches everything after the `/`
`\?` | a `?` or any other character specified after the backslash
When a glob pattern contains a path separator `/`, the full pathname is
matched. Otherwise the basename of a file or directory is matched in recursive
searches. For example, `*.h` matches `foo.h` and `bar/foo.h`. `bar/*.h`
matches `bar/foo.h` but not `foo.h` and not `bar/bar/foo.h`.
When a glob pattern begins with a `/`, files and directories are matched at the
working directory, not recursively. For example, use a leading `/` to force
`/*.h` to match `foo.h` but not `bar/foo.h`.
When a glob pattern ends with a `/`, directories are matched instead of files,
same as `--include-dir`.
When a glob starts with a `!` as specified with `-g!GLOB`, or specified in a
`FILE` with `--include-from=FILE` or `--exclude-from=FILE`, it is negated.
To view a list of inclusions and exclusions that were applied to a search, use
option `--stats`.
To list only readable files with names starting with `foo` in the working
directory, that contain `xyz`, without producing warning messages with `-s` and
`-l`:
ug -sl 'xyz' foo*
The same, but using deep recursion with inclusion constraints (note that
`-g'/foo*` is the same as `--include='/foo*'` and `-g'/foo*/'` is the same as
`--include-dir='/foo*'`, i.e. immediate subdirectories matching `/foo*` only):
ug -rl 'xyz' -g'/foo*' -g'/foo*/'
Note that `-r` is the default, we use it here to make the examples easier to
follow.
To exclude directory `bak` located in the working directory:
ug -rl 'xyz' -g'^/bak/'
To exclude all directoies `bak` at any directory level deep:
ug -rl 'xyz' -g'^bak/'
To only list files in the working directory and its subdirectory `doc`,
that contain `xyz` (note that `-g'/doc/'` is the same as
`--include-dir='/doc'`, i.e. immediate subdirectory `doc` only):
ug -rl 'xyz' -g'/doc/'
To only list files that are on a subdirectory path `doc` that includes
subdirectory `html` anywhere, that contain `xyz`:
ug -rl 'xyz' -g'doc/**/html/'
To only list files in the working directory and in the subdirectories `doc`
and `doc/latest` but not below, that contain `xyz`:
ug -rl 'xyz' -g'/doc/' -g'/doc/latest/'
To recursively list .cpp files in the working directory and any subdirectory
at any depth, that contain `xyz`:
ug -rl 'xyz' -g'*.cpp'
The same, but using a .gitignore-style glob that matches pathnames (globs with
`/`) instead of matching basenames (globs without `/`) in the recursive search:
ug -rl 'xyz' -g'**/*.cpp'
Same, but using option `-Ocpp` to match file name extensions:
ug -rl -Ocpp 'xyz'
To recursively list all files in the working directory and below that are not
ignored by a specific .gitignore file:
ug -rl '' --exclude-from=.gitignore
To recursively list all files in the working directory and below that are not
ignored by one or more .gitignore files, when any are present:
ug -rl '' --ignore-files
🔝 [Back to table of contents](#toc)
<a name="fs"/>
### Including or excluding mounted file systems from searches
--exclude-fs=MOUNTS
Exclude file systems specified by MOUNTS from recursive searches,
MOUNTS is a comma-separated list of mount points or pathnames of
directories on file systems. Note that --exclude-fs mounts take
priority over --include-fs mounts. This option may be repeated.
--include-fs=MOUNTS
Only file systems specified by MOUNTS are included in recursive
searches. MOUNTS is a comma-separated list of mount points or
pathnames of directories on file systems. --include-fs=. restricts
recursive searches to the file system of the working directory
only. Note that --exclude-fs mounts take priority over
--include-fs mounts. This option may be repeated.
These options control recursive searches across file systems by comparing
device numbers. Mounted devices and symbolic links to files and directories
located on mounted file systems may be included or excluded from recursive
searches by specifying a mount point or a pathname of any directory on the file
system to specify the applicable file system.
Note that a list of mounted file systems is typically stored in `/etc/mtab`.
To restrict recursive searches to the file system of the working directory
only, without crossing into other file systems (similar to `find` option `-x`):
ug -rl --include-fs=. 'xyz'
To exclude the file systems mounted at `/dev` and `/proc` from recursive
searches:
ug -rl --exclude-fs=/dev,/proc 'xyz'
To only include the file system associated with drive `d:` in recursive
searches:
ug -rl --include-fs=d:/ 'xyz'
To exclude `fuse` and `tmpfs` type file systems from recursive searches:
exfs=`ugrep -w -e fuse -e tmpfs /etc/mtab | ugrep -P '^\S+ (\S+)' --format='%,%1'`
ug -rl --exclude-fs="$exfs" 'xyz'
🔝 [Back to table of contents](#toc)
<a name="count"/>
### Counting the number of matches with -c and -co
-c, --count
Only a count of selected lines is written to standard output. If
-o or -u is specified, counts the number of patterns matched. If
-v is specified, counts the number of non-matching lines. If
--tree is specified, outputs directories in a tree-like format.
To count the number of lines in a file:
ug -c '' myfile.txt
To count the number of lines with `TODO`:
ug -c -w 'TODO' myfile.cpp
To count the total number of `TODO` in a file, use `-c` and `-o`:
ug -co -w 'TODO' myfile.cpp
To count the number of ASCII words in a file:
ug -co '[[:word:]]+' myfile.txt
To count the number of ASCII and Unicode words in a file:
ug -co '\w+' myfile.txt
To count the number of Unicode characters in a file:
ug -co '\p{Unicode}' myfile.txt
To count the number of zero bytes in a file:
ug -UX -co '\x00' image.jpg
🔝 [Back to table of contents](#toc)
<a name="fields"/>
### Displaying file, line, column, and byte offset info with -H, -n, -k, -b, and -T
-b, --byte-offset
The offset in bytes of a matched line is displayed in front of the
respective matched line. When used with option -u, displays the
offset in bytes of each pattern matched. Byte offsets are exact
for ASCII, UTF-8, and raw binary input. Otherwise, the byte offset
in the UTF-8 converted input is displayed.
-H, --with-filename
Always print the filename with output lines. This is the default
when there is more than one file to search.
-k, --column-number
The column number of a matched pattern is displayed in front of the
respective matched line, starting at column 1. Tabs are expanded
when columns are counted, see option --tabs.
-n, --line-number
Each output line is preceded by its relative line number in the
file, starting at line 1. The line number counter is reset for
each file processed.
-T, --initial-tab
Add a tab space to separate the file name, line number, column
number, and byte offset with the matched line.
To display the file name `-H`, line `-n`, and column `-k` numbers of matches in
`myfile.cpp`, with spaces and tabs to space the columns apart with `-T`:
ug -THnk 'main' myfile.cpp
To display the line with `-n` of word `main` in `myfile.cpp`:
ug -nw 'main' myfile.cpp
To display the entire file `myfile.cpp` with line `-n` numbers:
ug -n '' myfile.cpp
To recursively search for C++ files with `main`, showing the line and column
numbers of matches with `-n` and `-k`:
ug -r -nk -tc++ 'main'
To display the byte offset of matches with `-b`:
ug -r -b -tc++ 'main'
To display the line and column numbers of matches in XML with `--xml`:
ug -r -nk --xml -tc++ 'main'
🔝 [Back to table of contents](#toc)
<a name="color"/>
### Displaying colors with --color and paging the output with --pager
--color[=WHEN], --colour[=WHEN]
Mark up the matching text with the expression stored in the
GREP_COLOR or GREP_COLORS environment variable. The possible
values of WHEN can be `never', `always', or `auto', where `auto'
marks up matches only when output on a terminal. The default is
`auto'.
--colors=COLORS, --colours=COLORS
Use COLORS to mark up text. COLORS is a colon-separated list of
one or more parameters `sl=' (selected line), `cx=' (context line),
`mt=' (matched text), `ms=' (match selected), `mc=' (match
context), `fn=' (file name), `ln=' (line number), `cn=' (column
number), `bn=' (byte offset), `se=' (separator). Parameter values
are ANSI SGR color codes or `k' (black), `r' (red), `g' (green),
`y' (yellow), `b' (blue), `m' (magenta), `c' (cyan), `w' (white).
Upper case specifies background colors. A `+' qualifies a color as
bright. A foreground and a background color may be combined with
font properties `n' (normal), `f' (faint), `h' (highlight), `i'
(invert), `u' (underline). Parameter `hl' enables file name
hyperlinks. Parameter `rv' reverses the `sl=' and `cx=' parameters
when option -v is specified. Selectively overrides GREP_COLORS.
--tag[=TAG[,END]]
Disables colors to mark up matches with TAG. END marks the end of
a match if specified, otherwise TAG. The default is `___'.
--pager[=COMMAND]
When output is sent to the terminal, uses COMMAND to page through
the output. The default COMMAND is `less -R'. Enables --heading
and --line-buffered.
--pretty
When output is sent to a terminal, enables --color, --heading, -n,
--sort, --tree and -T when not explicitly disabled.
To change the color palette, set the `GREP_COLORS` environment variable or use
`--colors=COLORS`. The value is a colon-separated list of ANSI SGR parameters
that defaults to `cx=33:mt=1;31:fn=1;35:ln=1;32:cn=1;32:bn=1;32:se=36`:
param | result
----- | ------------------------------------------------------------------------
`sl=` | SGR substring for selected lines
`cx=` | SGR substring for context lines
`rv` | Swaps the `sl=` and `cx=` capabilities when `-v` is specified
`mt=` | SGR substring for matching text in any matching line
`ms=` | SGR substring for matching text in a selected line. The substring mt= by default
`mc=` | SGR substring for matching text in a context line. The substring mt= by default
`fn=` | SGR substring for file names
`ln=` | SGR substring for line numbers
`cn=` | SGR substring for column numbers
`bn=` | SGR substring for byte offsets
`se=` | SGR substring for separators
Multiple SGR codes may be specified for a single parameter when separated by a
semicolon, e.g. `mt=1;31` specifies bright red. The following SGR codes are
available on most color terminals:
code | c | effect | code | c | effect
---- | - | -------------------------- | ---- | -- | ----------------------------
0 | n | normal font and color | 2 | f | faint (not widely supported)
1 | h | highlighted bold font | 21 | H | highlighted bold off
4 | u | underline | 24 | U | underline off
7 | i | invert video | 27 | I | invert off
30 | k | black text | 90 | +k | bright gray text
31 | r | red text | 91 | +r | bright red text
32 | g | green text | 92 | +g | bright green text
33 | y | yellow text | 93 | +y | bright yellow text
34 | b | blue text | 94 | +b | bright blue text
35 | m | magenta text | 95 | +m | bright magenta text
36 | c | cyan text | 96 | +c | bright cyan text
37 | w | white text | 97 | +w | bright white text
40 | K | black background | 100 | +K | bright gray background
41 | R | dark red background | 101 | +R | bright red background
42 | G | dark green background | 102 | +G | bright green background
43 | Y | dark yellow backgrounda | 103 | +Y | bright yellow background
44 | B | dark blue background | 104 | +B | bright blue background
45 | M | dark magenta background | 105 | +M | bright magenta background
46 | C | dark cyan background | 106 | +C | bright cyan background
47 | W | dark white background | 107 | +W | bright white background
See Wikipedia [ANSI escape code - SGR parameters](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters)
For quick and easy color specification, the corresponding single-letter color
names may be used in place of numeric SGR codes. Semicolons are not required
to separate color names. Color names and numeric codes may be mixed.
For example, to display matches in underlined bright green on bright selected
lines, aiding in visualizing white space in matches and file names:
export GREP_COLORS='sl=1:cx=33:ms=1;4;32;100:mc=1;4;32:fn=1;32;100:ln=1;32:cn=1;32:bn=1;32:se=36'
The same, but with single-letter color names:
export GREP_COLORS='sl=h:cx=y:ms=hug+K:mc=hug:fn=hg+K:ln=hg:cn=hg:bn=hg:se=c'
Another color scheme that works well:
export GREP_COLORS='cx=hb:ms=hiy:mc=hic:fn=hi+y+K:ln=hg:cn=hg:bn=hg:se='
Modern Windows command interpreters support ANSI escape codes. Named or
numeric colors can be set with `SET GREP_COLORS`, for example:
SET GREP_COLORS=sl=1;37:cx=33:mt=1;31:fn=1;35:ln=1;32:cn=1;32:bn=1;32:se=36
To disable colors on Windows:
SET GREP_COLORS=""
Color intensities may differ per platform and per terminal program used, which
affects readability.
Option `-y` outputs every line of input, including non-matching lines as
context. The use of color helps distinguish matches from non-matching context.
To copy silver searcher's color palette:
export GREP_COLORS='mt=30;43:fn=1;32:ln=1;33:cn=1;33:bn=1;33'
To produce color-highlighted results (`--color` is redundance since it is the
default):
ug --color -r -n -k -tc++ 'FIXME.*'
To page through the results with pager (`less -R` by default):
ug --pager -r -n -k -tc++ 'FIXME'
To display a hexdump of a zip file itself (i.e. without decompressing), with
color-highlighted matches of the zip magic bytes `PK\x03\x04` (`--color` is
redundant since it is the default):
ug --color -y -UX 'PK\x03\x04' some.zip
To use predefined patterns to list all `#include` and `#define` in C++ files:
ug --pretty -r -n -tc++ -f c++/includes -f c++/defines
Same, but overriding the color of matches as inverted yellow (reverse video)
and headings with yellow on blue using `--pretty`:
ug --pretty --colors="ms=yi:fn=hyB" -r -n -tc++ -f c++/includes -f c++/defines
To list all `#define FOO...` macros in C++ files, color-highlighted:
ug --color=always -r -n -tc++ -f c++/defines | ug 'FOO.*'
Same, but restricted to `.cpp` files only:
ug --color=always -r -n -Ocpp -f c++/defines | ug 'FOO.*'
To search tarballs for matching names of PDF files (assuming bash is our shell):
for tb in *.tar *.tar.gz *.tgz; do echo "$tb"; tar tfz "$tb" | ugrep '.*\.pdf$'; done
🔝 [Back to table of contents](#toc)
<a name="json"/>
### Output matches in JSON, XML, CSV, C++
--cpp Output file matches in C++. See also options --format and -u.
--csv Output file matches in CSV. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
--json Output file matches in JSON. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
--xml Output file matches in XML. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
To recursively search for lines with `TODO` and display C++ file matches in
JSON with line number properties:
ug -tc++ -n --json 'TODO'
To recursively search for lines with `TODO` and display C++ file matches in
XML with line and column number attributes:
ug -tc++ -nk --xml 'TODO'
To recursively search for lines with `TODO` and display C++ file matches in CSV
format with file pathname, line number, and column number fields:
ug -tc++ --csv -Hnk 'TODO'
To extract a table from an HTML file and put it in C/C++ source code using
`-o`:
ug -o --cpp '<tr>.*</tr>' index.html > table.cpp
🔝 [Back to table of contents](#toc)
<a name="format"/>
### Customized output with --format
--format=FORMAT
Output FORMAT-formatted matches. For example --format='%f:%n:%O%~'
outputs matching lines `%O' with filename `%f` and line number `%n'
followed by a newline `%~'. If -P is specified, FORMAT may include
`%1' to `%9', `%[NUM]#' and `%[NAME]#' to output group captures. A
`%%' outputs `%'. See `ugrep --help format' and `man ugrep'
section FORMAT for details. When option -o is specified, option -u
is also enabled. Context options -A, -B, -C and -y are ignored.
-P, --perl-regexp
Interpret PATTERN as a Perl regular expression.
Use option `-P` to use group captures and backreferences. Capturing groups in
regex patterns are parenthesized expressions `(pattern)`. The first group is
referenced in `FORMAT` by `%1`, the second by `%2` and so on. Named captures
are of the form `(?<NAME>pattern)` and are referenced in `FORMAT` by
`%[NAME]#`.
The following output formatting options may be used. The `FORMAT` string
`%`-fields are listed in a table further below:
option | result
----------------------- | ------------------------------------------------------
`--format-begin=FORMAT` | `FORMAT` beginning the search
`--format-open=FORMAT` | `FORMAT` opening a file and a match was found
`--format=FORMAT` | `FORMAT` for each match in a file
`--format-close=FORMAT` | `FORMAT` closing a file and a match was found
`--format-end=FORMAT` | `FORMAT` ending the search
The following tables show the formatting options corresponding to `--csv`,
`--json`, and `--xml`.
#### `--csv`
option | format string (within quotes)
---------------- | -----------------------------
`--format-open` | `'%+'`
`--format` | `'%[,]$%H%N%K%B%V%~%u'`
#### `--json`
option | format string (within quotes)
---------------- | -----------------------------
`--format-begin` | `'['`
`--format-open` | `'%,%~ {%~ %[,%~ ]$%["file": ]H"matches": ['`
`--format` | `'%,%~ { %[, ]$%["line": ]N%["column": ]K%["offset": ]B"match": %J }%u'`
`--format-close` | `'%~ ]%~ }'`
`--format-end` | `'%~]%~'`
#### `--xml`
option | format string (within quotes)
---------------- | -----------------------------
`--format-begin` | `'<grep>%~'`
`--format-open` | `' <file%[]$%[ name=]H>%~'`
`--format` | `' <match%[\"]$%[ line=\"]N%[ column=\"]K%[ offset=\"]B>%X</match>%~%u'`
`--format-close` | `' </file>%~'`
`--format-end` | `'</grep>%~'`
### `--only-line-number`
option | format string (within quotes)
---------------- | -----------------------------
`--format-open` | `'%+'`
`--format` | `'%F%n%s%K%B%~%u'`
The following fields may be used in the `FORMAT` string:
field | output
----------------------- | ------------------------------------------------------
`%F` | if option `-H` is used: the file pathname and separator
`%[ARG]F` | if option `-H` is used: `ARG`, the file pathname and separator
`%f` | the file pathname
`%a` | the file basename without directory path
`%p` | the directory path to the file
`%z` | the pathname in a (compressed) archive, without `{` and `}`
`%H` | if option `-H` is used: the quoted pathname and separator, `\"` and `\\` replace `"` and `\`
`%[ARG]H` | if option `-H` is used: `ARG`, the quoted pathname and separator, `\"` and `\\` replace `"` and `\`
`%h` | the quoted file pathname, `\"` and `\\` replace `"` and `\`
`%N` | if option `-n` is used: the line number and separator
`%[ARG]N` | if option `-n` is used: `ARG`, the line number and separator
`%n` | the line number of the match
`%K` | if option `-k` is used: the column number and separator
`%[ARG]K` | if option `-k` is used: `ARG`, the column number and separator
`%k` | the column number of the match
`%B` | if option `-b` is used: the byte offset and separator
`%[ARG]B` | if option `-b` is used: `ARG`, the byte offset and separator
`%b` | the byte offset of the match
`%T` | if option `-T` is used: `ARG` and a tab character
`%[ARG]T` | if option `-T` is used: `ARG` and a tab character
`%t` | a tab character
`%[SEP]$` | set field separator to `SEP` for the rest of the format fields
`%[ARG]<` | if the first match: `ARG`
`%[ARG]>` | if not the first match: `ARG`
`%,` | if not the first match: a comma, same as `%[,]>`
`%:` | if not the first match: a colon, same as `%[:]>`
`%;` | if not the first match: a semicolon, same as `%[;]>`
`%│` | if not the first match: a vertical bar, same as `%[│]>`
`%S` | if not the first match: separator, see also `%[SEP]$`
`%[ARG]S` | if not the first match: `ARG` and separator, see also `%[SEP]$`
`%s` | the separator, see also `%[ARG]S` and `%[SEP]$`
`%~` | a newline character
`%+` | if option `--heading` is used: `%F` and a newline character, suppress all `%F` afterward
`%m` | the number of matches, sequential (or number of matching files with `--format-end`)
`%M` | the number of matching lines (or number of matching files with `--format-end`)
`%O` | the matching line is output as is (a raw string of bytes)
`%o` | the match is output as is (a raw string of bytes)
`%Q` | the matching line as a quoted string, `\"` and `\\` replace `"` and `\`
`%q` | the match as a quoted string, `\"` and `\\` replace `"` and `\`
`%C` | the matching line formatted as a quoted C/C++ string
`%c` | the match formatted as a quoted C/C++ string
`%J` | the matching line formatted as a quoted JSON string
`%j` | the match formatted as a quoted JSON string
`%V` | the matching line formatted as a quoted CSV string
`%v` | the match formatted as a quoted CSV string
`%X` | the matching line formatted as XML character data
`%x` | the match formatted as XML character data
`%w` | the width of the match, counting (wide) characters
`%d` | the size of the match, counting bytes
`%e` | the ending byte offset of the match
`%Z` | the edit distance cost of an approximate match with option `-Z`
`%u` | select unique lines only unless option -u is used
`%1` `%2` ... `%9` | the first regex group capture of the match, and so on up to group `%9`, requires option `-P`
`%[NUM]#` | the regex group capture `NUM`; requires option `-P`
`%[NUM]b` | the byte offset of the group capture `NUM`; requires option `-P`
`%[NUM]e` | the ending byte offset of the group capture `NUM`; requires option `-P`
`%[NUM]d` | the byte length of the group capture `NUM`; requires option `-P`
`%[NUM1\|NUM2\|...]#` | the first group capture `NUM` that matched; requires option `-P`
`%[NUM1\|NUM2\|...]b` | the byte offset of the first group capture `NUM` that matched; requires option `-P`.
`%[NUM1\|NUM2\|...]e` | the ending byte offset of the first group capture `NUM` that matched; requires option `-P`.
`%[NUM1\|NUM2\|...]d` | the byte length of the first group capture `NUM` that matched; requires option `-P`.
`%[NAME]#` | the `NAME`d group capture; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`
`%[NAME]b` | the byte offset of the `NAME`d group capture; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`.
`%[NAME]e` | the ending byte offset of the `NAME`d group capture; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`.
`%[NAME]d` | the byte length of the `NAME`d group capture; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`.
`%[NAME1\|NAME2\|...]#` | the first `NAME`d group capture that matched; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`
`%[NAME1\|NAME2\|...]b` | the byte offset of the first `NAME`d group capture that matched; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`
`%[NAME1\|NAME2\|...]e` | the ending byte offset of the first `NAME`d group capture that matched; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`
`%[NAME1\|NAME2\|...]d` | the byte length of the first `NAME`d group capture that matched; requires option `-P` and capturing pattern `(?<NAME>PATTERN)`
`%G` | list of group capture indices/names of the match (see note)
`%[TEXT1\|TEXT2\|...]G` | list of TEXT indexed by group capture indices that matched; requires option `-P`
`%g` | the group capture index of the match or 1 (see note)
`%[TEXT1\|TEXT2\|...]g` | the first TEXT indexed by the first group capture index that matched; requires option `-P`
`%%` | the percentage sign
Note:
- Formatted output is written without a terminating newline, unless `%~` or `\n`
is explicitly specified in the format string.
- The `[ARG]` part of a field is optional and may be omitted. When present,
the argument must be placed in `[]` brackets, for example `%[,]F` to output a
comma, the pathname, and a separator, when option `-H` is used.
- Fields `%[SEP]$` and `%u` are switches and do not write anything to the
output.
- The separator used by `%F`, `%H`, `%N`, `%K`, `%B`, `%S`, and `%G` may be
changed by preceding the field with a `%[SEP]$`. When `[SEP]` is not
provided, reverts the separator to the default separator or the separator
specified by `--separator`.
- Formatted output is written for each matching pattern, which means that a
line may be output multiple times when patterns match more than once on the
same line. When field `%u` is found anywhere in the specified format string,
matching lines are output only once unless option `-u`, `--ungroup`
is used or when a newline is matched.
- The group capture index value output by `%g` corresponds to the index of the
sub-pattern matched among the alternations in the pattern when option `-P` is
not used. For example `foo|bar` matches `foo` with index 1 and `bar` with
index 2. With option `-P`, the index corresponds to the number of the first
group captured in the specified pattern.
- The strings specified in the list `%[TEXT1|TEXT2|...]G` and
`%[TEXT1|TEXT2|...]g` should correspond to the group capture index (see the
note above), i.e. `TEXT1` is output for index 1, `TEXT2` is output for index
2, and so on. If the list is too short, the index value is output or the
name of a named group capture is output.
- Option `-T` and `--pretty` add right-justifying spacing to fields `%N` and
`%K` if no leading `[ARG]` part is specified.
- Field `%+` may be used in `--format-open` to output the pathname heading and
a newline break, respectively. Field `%+` suppresses `%a`, `%F`, `%f`,
`%H`, `%h` and `%p` output.
To output matching lines faster by omitting the header output and binary match
checks, using `--format` with field `%O` (output matching line as is) and field
`%~` (output newline):
ug --format='%O%~' 'href=' index.html
Same, but also displaying the line and column numbers:
ug --format='%n%k: %O%~' 'href=' index.html
Same, but display a line at most once when matching multiple patterns, unless
option `-u` is used:
ug --format='%u%n%k: %O%~' 'href=' index.html
To string together a list of unique line numbers of matches, separated by
commas with field `%,`:
ug --format='%u%,%n' 'href=' index.html
To output the matching part of a line only with field `%o` (or option `-o` with
field `%O`):
ug --format='%o%~' "href=[\"'][^\"'][\"']" index.html
To string together the pattern matches as CSV-formatted strings with field `%v`
separated by commas with field `%,`:
ug --format='%,%v' "href=[\"'][^\"'][\"']" index.html
To output matches in CSV (comma-separated values), the same as option `--csv`
(works with options `-H`, `-n`, `-k`, `-b` to add CSV values):
ug --format='"%[,]$%H%N%K%B%V%~%u"' 'href=' index.html
To output matches in AckMate format:
ug --format=":%f%~%n;%k %w:%O%~" 'href=' index.html
To output the sub-pattern indices 1, 2, and 3 on the left to the match for the
three patterns `foo`, `bar`, and `baz` in file `foobar.txt`:
ug --format='%g: %o%~' 'foo|bar|baz' foobar.txt
Same, but using a file `foos` containing three lines with `foo`, `bar`, and
`baz`, where option `-F` is used to match strings instead of regex:
ug -F -f foos --format='%g: %o%~' foobar.txt
To output `one`, `two`, and `a word` for the sub-patterns `[fF]oo`, `[bB]ar`,
and any other word `\w+`, respectively, using argument `[one|two|a word]` with
field `%g` indexed by sub-pattern (or group captures with option `-P`):
ug --format='%[one|two|a word]g%~' '([fF]oo)|([bB]ar)|(\w+)' foobar.txt
To output a list of group capture indices with `%G` separated by the word `and`
instead of the default colons with `%[ and ]$`, followed by the matching line:
ug -P --format='%[ and ]$%G%$%s%O%~' '(foo)|(ba((r)|(z)))' foobar.txt
Same, but showing names instead of numbers:
ug -P --format='%[ and ]$%[foo|ba|r|z]G%$%s%O%~' '(foo)|(ba(?:(r)|(z)))' foobar.txt
Note that option `-P` is required for general use of group captures for
sub-patterns. Named sub-pattern matches may be used with PCRE2 and shown in
the output:
ug -P --format='%[ and ]$%G%$%s%O%~' '(?P<foo>foo)|(?P<ba>ba(?:(?P<r>r)|(?P<z>z)))' foobar.txt
🔝 [Back to table of contents](#toc)
<a name="replace"/>
### Replacing matches with -P --replace and --format using backreferences
--replace=FORMAT
Replace matching patterns in the output by the specified FORMAT
with `%' fields. If -P is specified, FORMAT may include `%1' to
`%9', `%[NUM]#' and `%[NAME]#' to output group captures. A `%%'
outputs `%' and `%~' outputs a newline. See option --format,
`ugrep --help format' and `man ugrep' section FORMAT for details.
-y, --any-line
Any line is output (passthru). Non-matching lines are output as
context with a `-' separator. See also options -A, -B, and -C.
-P, --perl-regexp
Interpret PATTERN as a Perl regular expression.
--format=FORMAT
Output FORMAT-formatted matches. For example --format='%f:%n:%O%~'
outputs matching lines `%O' with filename `%f` and line number `%n'
followed by a newline `%~'. If -P is specified, FORMAT may include
`%1' to `%9', `%[NUM]#' and `%[NAME]#' to output group captures. A
`%%' outputs `%'. See `ugrep --help format' and `man ugrep'
section FORMAT for details. When option -o is specified, option -u
is also enabled. Context options -A, -B, -C and -y are ignored.
See [customized output with --format](#format) for details on the `FORMAT`
fields.
For option `-o`, the replacement is not automatically followed by a newline to
allow for more flexibility in replacements. To output a newline, use `%~` in
the `FORMAT` string.
Use option `-P` to use group captures and backreferences. Capturing groups in
regex patterns are parenthesized expressions `(pattern)` and the first is
referenced in `FORMAT` by `%1`, the second by `%2` and so on. Named captures
are of the form `(?<NAME>pattern)` and are referenced in `FORMAT` by
`%[NAME]#`.
To display pattern matches with their sequential match number using
`--replace='%m:%o'` where `%m` is the sequential match number and `%o` is the
pattern matched:
ug --replace='%m:%o' pattern myfile.txt
Same, but passing the file through with option `-y`, while applying the
replacements to the output:
ug -y --replace='%m:%o' pattern myfile.txt
To extract table cells from an HTML file using Perl matching (`-P`) to support
group captures with lazy quantifier `(.*?)`, and translate the matches to a
comma-separated list with format `%,%1` (conditional comma and group capture):
ug -P -o '<td>(.*?)</td>' --replace='%,%1' index.html
Same, but using `--format='%,%1'` instead and we do not need `-o` (note that
`--replace` color-highlights matches shown on a terminal but `--format` does
not):
ug -P '<td>(.*?)</td>' --format='%,%1' index.html
Same, but displaying the formatted matches line-by-line, with `--replace` or
with `--format`:
ug -P -o '<td>(.*?)</td>' --replace='%,%1' index.html
ug -P '<td>(.*?)</td>' --format='%1%~' index.html
To collect all `href` URLs from all HTML and PHP files down the working
directory, then sort them:
ug -r -thtml,php -P '<[^<>]+href\h*=\h*.([^\x27"]+).' --format='%1%~' | sort -u
Same, but much easier by using the predefined `html/href` pattern:
ug -r -thtml,php -P -f html/href --format='%1%~' | sort -u
Same, but in this case select `<script>` `src` URLs when referencing `http` and
`https` sites:
ug -r -thtml,php -P '<script.*src\h*=\h*.(https?:[^\x27"]+).' --format='%1%~' | sort -u
🔝 [Back to table of contents](#toc)
<a name="max"/>
### Limiting the number of matches with -1,-2...-9, -K, -m, and --max-files
--depth=[MIN,][MAX], -1, -2, -3, ... -9, --10, --11, --12, ...
Restrict recursive searches from MIN to MAX directory levels deep,
where -1 (--depth=1) searches the specified path without recursing
into subdirectories. Note that -3 -5, -3-5, and -35 search 3 to 5
levels deep. Enables -r if -R or -r is not specified.
-K [MIN,][MAX], --range=[MIN,][MAX], --min-line=MIN, --max-line=MAX
Start searching at line MIN, stop at line MAX when specified.
-m [MIN,][MAX], --min-count=MIN, --max-count=MAX
Require MIN matches, stop after MAX matches when specified. Output
MIN to MAX matches. For example, -m1 outputs the first match and
-cm1, (with comma) counts non-zero matches. See also option -K.
--max-files=NUM
Restrict the number of files matched to NUM. Note that --sort or
-J1 may be specified to produce replicable results. If --sort is
specified, the number of threads spawned is limited to NUM.
--sort[=KEY]
Displays matching files in the order specified by KEY in recursive
searches. Normally the ug command sorts by name whereas the ugrep
batch command displays matches in no particular order to improve
performance. The sort KEY can be `name' to sort by pathname
(default), `best' to sort by best match with option -Z (sort by
best match requires two passes over files, which is expensive),
`size' to sort by file size, `used' to sort by last access time,
`changed' to sort by last modification time and `created' to sort
by creation time. Sorting is reversed with `rname', `rbest',
`rsize', `rused', `rchanged', or `rcreated'. Archive contents are
not sorted. Subdirectories are sorted and displayed after matching
files. FILE arguments are searched in the same order as specified.
To show only the first 10 matches of `FIXME` in C++ files in the working
directory and all subdirectories below:
ug -r -m10 -tc++ FIXME
Same, but recursively search up to two directory levels, meaning that `./` and
`./sub/` are visited but not deeper:
ug -2 -m10 -tc++ FIXME
To show only the first two files that have one or more matches of `FIXME` in
the list of files sorted by pathname, using `--max-files=2`:
ug --sort -r --max-files=2 -tc++ FIXME
To search file `install.sh` for the occurrences of the word `make` after the
first line, we use `-K` with line number 2 to start searching, where `-n` shows
the line numbers in the output:
ug -n -K2 -w make install.sh
Same, but restricting the search to lines 2 to 40 (inclusive):
ug -n -K2,40 -w make install.sh
Same, but showing all lines 2 to 40 with `-y`:
ug -y -n -K2,40 -w make install.sh
Same, but showing only the first four matching lines after line 2, with one
line of context:
ug -n -C1 -K2 -m4 -w make install.sh
🔝 [Back to table of contents](#toc)
<a name="empty"/>
### Matching empty patterns with -Y
-Y, --empty
Permits empty matches. By default, empty matches are disabled,
unless a pattern begins with `^' or ends with `$'. Note that -Y
when specified with an empty-matching pattern, such as x? and x*,
match all input, not only lines containing the character `x'.
Option `-Y` permits empty pattern matches, like GNU/BSD grep. This option is
introduced by **ugrep** to prevent accidental matching with empty patterns:
empty-matching patterns such as `x?` and `x*` match all input, not only lines
with `x`. By default, without `-Y`, patterns match lines with at least one `x`
as intended.
This option is automatically enabled when a pattern starts with `^` or ends
with `$` is specified. For example, `^\h*$` matches blank lines, including
empty lines.
To recursively list files in the working directory with blank lines, i.e. lines
with white space only, including empty lines (note that option `-Y` is
implicitly enabled since the pattern starts with `^` and ends with `$`):
ug -l '^\h*$'
🔝 [Back to table of contents](#toc)
<a name="case"/>
### Case-insentitive matching with -i and -j
-i, --ignore-case
Perform case insensitive matching. By default, ugrep is case
sensitive. By default, this option applies to ASCII letters only.
Use options -P and -i for Unicode case insensitive matching.
-j, --smart-case
Perform case insensitive matching like option -i, unless a pattern
is specified with a literal ASCII upper case letter.
To match `todo` in `myfile.cpp` regardless of case:
ug -i 'todo' myfile.txt
To match `todo XXX` with `todo` in any case but `XXX` as given, with pattern
`(?i:todo)` to match `todo` ignoring case:
ug '(?i:todo) XXX' myfile.cpp
🔝 [Back to table of contents](#toc)
<a name="sort"/>
### Sort files by name, best match, size, and time
--sort[=KEY]
Displays matching files in the order specified by KEY in recursive
searches. Normally the ug command sorts by name whereas the ugrep
batch command displays matches in no particular order to improve
performance. The sort KEY can be `name' to sort by pathname
(default), `best' to sort by best match with option -Z (sort by
best match requires two passes over files, which is expensive),
`size' to sort by file size, `used' to sort by last access time,
`changed' to sort by last modification time and `created' to sort
by creation time. Sorting is reversed with `rname', `rbest',
`rsize', `rused', `rchanged', or `rcreated'. Archive contents are
not sorted. Subdirectories are sorted and displayed after matching
files. FILE arguments are searched in the same order as specified.
Matching files are displayed in the order specified by `--sort` per directory
searched. By default, the `ug` command sorts by name whereas the output of the
`ugrep` command is not sorted to improve performance, unless option `-Q` is
used which sorts files by name. An optimized sorting method and strategy are
implemented in the asynchronous output class to keep the overhead of sorting
very low. Directories are displayed after files are displayed first, when
recursing, which visually aids the user in finding the "closest" matching files
first at the top of the displayed results.
To recursively search for C++ files that match `main` and sort them by date
created:
ug --sort=created -tc++ 'main'
Same, but sorted by time changed from most recent to oldest:
ug --sort=rchanged -tc++ 'main'
🔝 [Back to table of contents](#toc)
<a name="tips"/>
### Tips for advanced users
When searching non-binary files only, the binary content check is disabled with
option `-a` (`--text`) to speed up searching and displaying pattern matches.
For example, searching for lines with `int` in C++ source code:
ug -r -a -Ocpp -w 'int'
If a file has potentially many pattern matches, but each match is only one a
single line, then option `-u` (`--ungroup`) can speed this up:
ug -r -a -u -Opython -w 'def'
Even greater speeds can be achieved with `--format` when searching files with
many matches. For example, `--format='%O%~'` displays matching lines for each
match on that line, while `--format='%o%~'` displays the matching part only.
Note that the `--format` option does not check for binary matches, so the
output is always "as is". To match text and binary, you can use
`--format='%C%~'` to display matches formatted as quoted C++ strings with
escapes. To display a line at most once (unless option `-u` is used), add the
`%u` (unique) field to the format string, e.g. `--format='%u%O%~'`.
For example, to match all words recursively in the working directory with line
and column numbers, where `%n` is the line number, `%k` is the column number,
`%o` is the match (only matching), and `%~` is a newline:
ug -r --format='%n,%k:%o%~' '\w+'
🔝 [Back to table of contents](#toc)
<a name="more"/>
### More examples
To search for pattern `-o` in `script.sh` using `-e` to explicitly specify a
pattern to prevent pattern `-o` from being interpreted as an option:
ug -n -e '-o' script.sh
Alternatively, using `--` to end the list of command arguments:
ug -n -- '-o' script.sh
To recursively list all text files (.txt and .md) that do not properly end with
a `\n` (`-o` is required to match `\n` or `\z`):
ug -L -o -Otext '\n\z'
To list all markdown sections in text files (.text, .txt, .TXT, and .md):
ug -o -ttext -e '^.*(?=\r?\n(===|---))' -e '^#{1,6}\h+.*'
To display multi-line backtick and indented code blocks in markdown files with
their line numbers, using a lazy quantifier `*?` to make the pattern compact:
ug -n -ttext -e '^```(.|\n)*?\n```' -e '^(\t|[ ]{4}).*'
To find mismatched code (a backtick without matching backtick on the same line)
in markdown:
ug -n -ttext -e '`[^`]+' -N '`[^`]*`'
🔝 [Back to table of contents](#toc)
<a name="man"/>
### Man page
UGREP(1) User Commands UGREP(1)
NAME
ugrep, ug -- file pattern searcher
SYNOPSIS
ugrep [OPTIONS] [-A NUM] [-B NUM] [-C NUM] [-y] [-Q|PATTERN] [-f FILE]
[-e PATTERN] [-N PATTERN] [-t TYPES] [-g GLOBS] [--sort[=KEY]]
[--color[=WHEN]|--colour[=WHEN]] [--pager[=COMMAND]] [FILE ...]
DESCRIPTION
The ugrep utility searches any given input files, selecting lines that
match one or more patterns. By default, a pattern matches an input line
if the regular expression (RE) matches the input line. A pattern matches
multiple input lines if the RE in the pattern matches one or more
newlines in the input. An empty pattern matches every line. Each input
line that matches at least one of the patterns is written to the standard
output.
The ug command is intended for interactive searching, using a .ugrep
configuration file located in the working directory or home directory,
see CONFIGURATION. ug is equivalent to ugrep --config and sorts files by
name by default.
ugrep accepts input of various encoding formats and normalizes the output
to UTF-8. When a UTF byte order mark is present in the input, the input
is automatically normalized; otherwise, ugrep assumes the input is ASCII,
UTF-8, or raw binary. An input encoding format may be specified with
option --encoding.
If no FILE arguments are specified and standard input is read from a
terminal, recursive searches are performed as if -r is specified. To
force reading from standard input, specify `-' as a FILE argument.
Directories specified as FILE arguments are searched without recursing
deeper into subdirectories, unless -R, -r, or -2...-9 is specified to
search subdirectories.
Hidden files and directories are ignored in recursive searches. Option
-. (--hidden) includes hidden files and directories in recursive
searches.
A query interface is opened with -Q (--query) to interactively specify
search patterns and view search results. Note that a PATTERN argument
cannot be specified in this case. To specify one or more patterns with
-Q to start searching, use -e PATTERN.
Option -f FILE matches patterns specified in FILE. If FILE is large and
defines complex regular expression patterns, then option -P (Perl
matching) may improve performance (this omits POSIX DFA construction.)
ugrep --help WHAT displays help on options related to WHAT; --help format
displays help on --format and --replace formatting; --help regex displays
help on regular expression syntax and conventions; --help globs displays
help on glob patterns to select files to search; --help fuzzy displays
help on fuzzy (approximate) searching.
The following options are available:
-A NUM, --after-context=NUM
Output NUM lines of trailing context after matching lines. Places
a --group-separator between contiguous groups of matches. If -o
is specified, output the match with context to fit NUM columns
after the match or shortens the match. See also options -B, -C
and -y.
-a, --text
Process a binary file as if it were text. This is equivalent to
the --binary-files=text option. This option might output binary
garbage to the terminal, which can have problematic consequences
if the terminal driver interprets some of it as commands.
--and [-e] PATTERN ... -e PATTERN
Specify additional patterns to match. Patterns must be specified
with -e. Each -e PATTERN following this option is considered an
alternative pattern to match, i.e. each -e is interpreted as an OR
pattern. For example, -e A -e B --and -e C -e D matches lines
with (`A' or `B') and (`C' or `D'). Note that multiple -e PATTERN
are alternations that bind more tightly together than --and.
Option --stats displays the search patterns applied. See also
options --not, --andnot, --bool, --files and --lines.
--andnot [-e] PATTERN
Combines --and --not. See also options --and, --not and --bool.
-B NUM, --before-context=NUM
Output NUM lines of leading context before matching lines. Places
a --group-separator between contiguous groups of matches. If -o
is specified, output the match with context to fit NUM columns
before the match or shortens the match. See also options -A, -C
and -y.
-b, --byte-offset
The offset in bytes of a matched line is displayed in front of the
respective matched line. If -u is specified, displays the offset
for each pattern matched on the same line. Byte offsets are exact
for ASCII, UTF-8 and raw binary input. Otherwise, the byte offset
in the UTF-8 normalized input is displayed.
--binary-files=TYPE
Controls searching and reporting pattern matches in binary files.
TYPE can be `binary', `without-match`, `text`, `hex` and
`with-hex'. The default is `binary' to search binary files and to
report a match without displaying the match. `without-match'
ignores binary matches. `text' treats all binary files as text,
which might output binary garbage to the terminal, which can have
problematic consequences if the terminal driver interprets some of
it as commands. `hex' reports all matches in hexadecimal.
`with-hex' only reports binary matches in hexadecimal, leaving
text matches alone. A match is considered binary when matching a
zero byte or invalid UTF. Short options are -a, -I, -U, -W and
-X.
--bool, -%
Specifies Boolean query patterns. A Boolean query pattern is
composed of `AND', `OR', `NOT' operators and grouping with `('
`)'. Spacing between subpatterns is the same as `AND', `|' is the
same as `OR' and a `-' is the same as `NOT'. The `OR' operator
binds more tightly than `AND'. For example, --bool 'A|B C|D'
matches lines with (`A' or `B') and (`C' or `D'), --bool 'A -B'
matches lines with `A' and not `B'. Operators `AND', `OR', `NOT'
require proper spacing. For example, --bool 'A OR B AND C OR D'
matches lines with (`A' or `B') and (`C' or `D'), --bool 'A AND
NOT B' matches lines with `A' without `B'. Quoted subpatterns are
matched literally as strings. For example, --bool 'A "AND"|"OR"'
matches lines with `A' and also either `AND' or `OR'. Parenthesis
are used for grouping. For example, --bool '(A B)|C' matches
lines with `A' and `B', or lines with `C'. Note that all
subpatterns in a Boolean query pattern are regular expressions,
unless -F is specified. Options -E, -F, -G, -P and -Z can be
combined with --bool to match subpatterns as strings or regular
expressions (-E is the default.) This option does not apply to -f
FILE patterns. Option --stats displays the search patterns
applied. See also options --and, --andnot, --not, --files and
--lines.
--break
Adds a line break between results from different files. This
option is enabled by --pretty when the output is sent to a
terminal.
-C NUM, --context=NUM
Output NUM lines of leading and trailing context surrounding each
matching line. Places a --group-separator between contiguous
groups of matches. If -o is specified, output the match with
context to fit NUM columns before and after the match or shortens
the match. See also options -A, -B and -y.
-c, --count
Only a count of selected lines is written to standard output. If
-o or -u is specified, counts the number of patterns matched. If
-v is specified, counts the number of non-matching lines. If
--tree is specified, outputs directories in a tree-like format.
--color[=WHEN], --colour[=WHEN]
Mark up the matching text with the expression stored in the
GREP_COLOR or GREP_COLORS environment variable. WHEN can be
`never', `always', or `auto', where `auto' marks up matches only
when output on a terminal. The default is `auto'.
--colors=COLORS, --colours=COLORS
Use COLORS to mark up text. COLORS is a colon-separated list of
one or more parameters `sl=' (selected line), `cx=' (context
line), `mt=' (matched text), `ms=' (match selected), `mc=' (match
context), `fn=' (file name), `ln=' (line number), `cn=' (column
number), `bn=' (byte offset), `se=' (separator). Parameter values
are ANSI SGR color codes or `k' (black), `r' (red), `g' (green),
`y' (yellow), `b' (blue), `m' (magenta), `c' (cyan), `w' (white).
Upper case specifies background colors. A `+' qualifies a color
as bright. A foreground and a background color may be combined
with font properties `n' (normal), `f' (faint), `h' (highlight),
`i' (invert), `u' (underline). Parameter `hl' enables file name
hyperlinks. Parameter `rv' reverses the `sl=' and `cx='
parameters when option -v is specified. Selectively overrides
GREP_COLORS.
--config[=FILE], ---[FILE]
Use configuration FILE. The default FILE is `.ugrep'. The
working directory is checked first for FILE, then the home
directory. The options specified in the configuration FILE are
parsed first, followed by the remaining options specified on the
command line.
--confirm
Confirm actions in -Q query mode. The default is confirm.
--cpp Output file matches in C++. See also options --format and -u.
--csv Output file matches in CSV. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
-D ACTION, --devices=ACTION
If an input file is a device, FIFO or socket, use ACTION to
process it. By default, ACTION is `skip', which means that
devices are silently skipped. If ACTION is `read', devices read
just as if they were ordinary files.
-d ACTION, --directories=ACTION
If an input file is a directory, use ACTION to process it. By
default, ACTION is `skip', i.e., silently skip directories unless
specified on the command line. If ACTION is `read', warn when
directories are read as input. If ACTION is `recurse', read all
files under each directory, recursively, following symbolic links
only if they are on the command line. This is equivalent to the
-r option. If ACTION is `dereference-recurse', read all files
under each directory, recursively, following symbolic links. This
is equivalent to the -R option.
--depth=[MIN,][MAX], -1, -2, -3, ... -9, --10, --11, --12, ...
Restrict recursive searches from MIN to MAX directory levels deep,
where -1 (--depth=1) searches the specified path without recursing
into subdirectories. Note that -3 -5, -3-5, and -35 search 3 to 5
levels deep. Enables -r if -R or -r is not specified.
--dotall
Dot `.' in regular expressions matches anything, including
newline. Note that `.*' matches all input and should not be used.
-E, --extended-regexp
Interpret patterns as extended regular expressions (EREs). This is
the default.
-e PATTERN, --regexp=PATTERN
Specify a PATTERN used during the search of the input: an input
line is selected if it matches any of the specified patterns.
Note that longer patterns take precedence over shorter patterns.
This option is most useful when multiple -e options are used to
specify multiple patterns, when a pattern begins with a dash
(`-'), to specify a pattern after option -f or after the FILE
arguments.
--encoding=ENCODING
The encoding format of the input. The default ENCODING is binary
and UTF-8 which are the same. Note that option -U specifies
binary PATTERN matching (text matching is the default.) ENCODING
can be: `binary', `ASCII', `UTF-8', `UTF-16', `UTF-16BE',
`UTF-16LE', `UTF-32', `UTF-32BE', `UTF-32LE', `LATIN1',
`ISO-8859-1', `ISO-8859-2', `ISO-8859-3', `ISO-8859-4',
`ISO-8859-5', `ISO-8859-6', `ISO-8859-7', `ISO-8859-8',
`ISO-8859-9', `ISO-8859-10', `ISO-8859-11', `ISO-8859-13',
`ISO-8859-14', `ISO-8859-15', `ISO-8859-16', `MAC', `MACROMAN',
`EBCDIC', `CP437', `CP850', `CP858', `CP1250', `CP1251', `CP1252',
`CP1253', `CP1254', `CP1255', `CP1256', `CP1257', `CP1258',
`KOI8-R', `KOI8-U', `KOI8-RU'.
--exclude=GLOB
Skip files whose name matches GLOB using wildcard matching, same
as -g ^GLOB. GLOB can use **, *, ?, and [...] as wildcards and \
to quote a wildcard or backslash character literally. When GLOB
contains a `/', full pathnames are matched. Otherwise basenames
are matched. When GLOB ends with a `/', directories are excluded
as if --exclude-dir is specified. Otherwise files are excluded.
Note that --exclude patterns take priority over --include
patterns. GLOB should be quoted to prevent shell globbing. This
option may be repeated.
--exclude-dir=GLOB
Exclude directories whose name matches GLOB from recursive
searches, same as -g ^GLOB/. GLOB can use **, *, ?, and [...] as
wildcards and \ to quote a wildcard or backslash character
literally. When GLOB contains a `/', full pathnames are matched.
Otherwise basenames are matched. Note that --exclude-dir patterns
take priority over --include-dir patterns. GLOB should be quoted
to prevent shell globbing. This option may be repeated.
--exclude-from=FILE
Read the globs from FILE and skip files and directories whose name
matches one or more globs. A glob can use **, *, ?, and [...] as
wildcards and \ to quote a wildcard or backslash character
literally. When a glob contains a `/', full pathnames are
matched. Otherwise basenames are matched. When a glob ends with
a `/', directories are excluded as if --exclude-dir is specified.
Otherwise files are excluded. A glob starting with a `!'
overrides previously-specified exclusions by including matching
files. Lines starting with a `#' and empty lines in FILE are
ignored. When FILE is a `-', standard input is read. This option
may be repeated.
--exclude-fs=MOUNTS
Exclude file systems specified by MOUNTS from recursive searches,
MOUNTS is a comma-separated list of mount points or pathnames of
directories on file systems. Note that --exclude-fs mounts take
priority over --include-fs mounts. This option may be repeated.
-F, --fixed-strings
Interpret pattern as a set of fixed strings, separated by
newlines, any of which is to be matched. This makes ugrep behave
as fgrep. If a PATTERN is specified, or -e PATTERN or -N PATTERN,
then this option has no effect on -f FILE patterns to allow -f
FILE patterns to narrow or widen the scope of the PATTERN search.
-f FILE, --file=FILE
Read newline-separated patterns from FILE. White space in
patterns is significant. Empty lines in FILE are ignored. If
FILE does not exist, the GREP_PATH environment variable is used as
path to FILE. If that fails, looks for FILE in
/usr/local/share/ugrep/patterns. When FILE is a `-', standard
input is read. Empty files contain no patterns; thus nothing is
matched. This option may be repeated.
--filter=COMMANDS
Filter files through the specified COMMANDS first before
searching. COMMANDS is a comma-separated list of `exts:command
[option ...]', where `exts' is a comma-separated list of filename
extensions and `command' is a filter utility. The filter utility
should read from standard input and write to standard output.
Files matching one of `exts' are filtered. When `exts' is `*',
files with non-matching extensions are filtered. One or more
`option' separated by spacing may be specified, which are passed
verbatim to the command. A `%' as `option' expands into the
pathname to search. For example, --filter='pdf:pdftotext % -'
searches PDF files. The `%' expands into a `-' when searching
standard input. Option --label=.ext may be used to specify
extension `ext' when searching standard input.
--filter-magic-label=[+]LABEL:MAGIC
Associate LABEL with files whose signature "magic bytes" match the
MAGIC regex pattern. Only files that have no filename extension
are labeled, unless +LABEL is specified. When LABEL matches an
extension specified in --filter=COMMANDS, the corresponding
command is invoked. This option may be repeated.
--format=FORMAT
Output FORMAT-formatted matches. For example
--format='%f:%n:%O%~' outputs matching lines `%O' with filename
`%f` and line number `%n' followed by a newline `%~'. If -P is
specified, FORMAT may include `%1' to `%9', `%[NUM]#' and
`%[NAME]#' to output group captures. A `%%' outputs `%'. See
`ugrep --help format' and `man ugrep' section FORMAT for details.
When option -o is specified, option -u is also enabled. Context
options -A, -B, -C and -y are ignored.
--free-space
Spacing (blanks and tabs) in regular expressions are ignored.
-G, --basic-regexp
Interpret patterns as basic regular expressions (BREs), i.e. make
ugrep behave as traditional grep.
-g GLOBS, --glob=GLOBS
Search only files whose name matches the specified comma-separated
list of GLOBS, same as --include='glob' for each `glob' in GLOBS.
When a `glob' is preceded by a `!' or a `^', skip files whose name
matches `glob', same as --exclude='glob'. When `glob' contains a
`/', full pathnames are matched. Otherwise basenames are matched.
When `glob' ends with a `/', directories are matched, same as
--include-dir='glob' and --exclude-dir='glob'. A leading `/'
matches the working directory. This option may be repeated and
may be combined with options -M, -O and -t to expand searches.
See `ugrep --help globs' and `man ugrep' section GLOBBING for
details.
--group-separator[=SEP]
Use SEP as a group separator for context options -A, -B and -C.
The default is a double hyphen (`--').
-H, --with-filename
Always print the filename with output lines. This is the default
when there is more than one file to search.
-h, --no-filename
Never print filenames with output lines. This is the default when
there is only one file (or only standard input) to search.
--heading, -+
Group matches per file. Adds a heading and a line break between
results from different files. This option is enabled by --pretty
when the output is sent to a terminal.
--help [WHAT], -? [WHAT]
Display a help message, specifically on WHAT when specified. In
addition, `--help format' displays an overview of FORMAT fields,
`--help regex' displays an overview of regular expressions and
`--help globs' displays an overview of glob syntax and
conventions.
--hexdump=[1-8][a][bch][A[NUM]][B[NUM]][C[NUM]]
Output matches in 1 to 8 columns of 8 hexadecimal octets. The
default is 2 columns or 16 octets per line. Option `a' outputs a
`*' for all hex lines that are identical to the previous hex line,
`b' removes all space breaks, `c' removes the character column,
`h' removes hex spacing, `A' includes up to NUM hex lines after
the match, `B' includes up to NUM hex lines before the match and
`C' includes up to NUM hex lines. When NUM is omitted, the
matching line is included in the output. See also options -U, -W
and -X.
--hidden, -.
Search hidden files and directories.
--hyperlink[=[PREFIX][+]]
Hyperlinks are enabled for file names when colors are enabled.
Same as --colors=hl. When PREFIX is specified, replaces file://
with PREFIX:// in the hyperlink. A `+' includes the line number
in the hyperlink and when option -k is specified, the column
number.
-I, --ignore-binary
Ignore matches in binary files. This option is equivalent to the
--binary-files=without-match option.
-i, --ignore-case
Perform case insensitive matching. By default, ugrep is case
sensitive. By default, this option applies to ASCII letters only.
Use options -P and -i for Unicode case insensitive matching.
--ignore-files[=FILE]
Ignore files and directories matching the globs in each FILE that
is encountered in recursive searches. The default FILE is
`.gitignore'. Matching files and directories located in the
directory of a FILE's location and in directories below are
ignored by temporarily extending the --exclude and --exclude-dir
globs, as if --exclude-from=FILE is locally enforced. Globbing
syntax is the same as the --exclude-from=FILE gitignore syntax;
directories are excluded when the glob ends in a `/', same as git.
Files and directories explicitly specified as command line
arguments are never ignored. This option may be repeated with
additional files.
--include=GLOB
Search only files whose name matches GLOB using wildcard matching,
same as -g GLOB. GLOB can use **, *, ?, and [...] as wildcards
and \ to quote a wildcard or backslash character literally. When
GLOB contains a `/', full pathnames are matched. Otherwise
basenames are matched. When GLOB ends with a `/', directories are
included as if --include-dir is specified. Otherwise files are
included. Note that --exclude patterns take priority over
--include patterns. GLOB should be quoted to prevent shell
globbing. This option may be repeated.
--include-dir=GLOB
Only directories whose name matches GLOB are included in recursive
searches, same as -g GLOB/. GLOB can use **, *, ?, and [...] as
wildcards and \ to quote a wildcard or backslash character
literally. When GLOB contains a `/', full pathnames are matched.
Otherwise basenames are matched. Note that --exclude-dir patterns
take priority over --include-dir patterns. GLOB should be quoted
to prevent shell globbing. This option may be repeated.
--include-from=FILE
Read the globs from FILE and search only files and directories
whose name matches one or more globs. A glob can use **, *, ?,
and [...] as wildcards and \ to quote a wildcard or backslash
character literally. When a glob contains a `/', full pathnames
are matched. Otherwise basenames are matched. When a glob ends
with a `/', directories are included as if --include-dir is
specified. Otherwise files are included. A glob starting with a
`!' overrides previously-specified inclusions by excluding
matching files. Lines starting with a `#' and empty lines in FILE
are ignored. When FILE is a `-', standard input is read. This
option may be repeated.
--include-fs=MOUNTS
Only file systems specified by MOUNTS are included in recursive
searches. MOUNTS is a comma-separated list of mount points or
pathnames of directories on file systems. --include-fs=.
restricts recursive searches to the file system of the working
directory only. Note that --exclude-fs mounts take priority over
--include-fs mounts. This option may be repeated.
-J NUM, --jobs=NUM
Specifies the number of threads spawned to search files. By
default an optimum number of threads is spawned to search files
simultaneously. -J1 disables threading: files are searched in the
same order as specified.
-j, --smart-case
Perform case insensitive matching like option -i, unless a pattern
is specified with a literal ASCII upper case letter.
--json Output file matches in JSON. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
-K [MIN,][MAX], --range=[MIN,][MAX], --min-line=MIN, --max-line=MAX
Start searching at line MIN, stop at line MAX when specified.
-k, --column-number
The column number of a matched pattern is displayed in front of
the respective matched line, starting at column 1. Tabs are
expanded when columns are counted, see also option --tabs.
-L, --files-without-match
Only the names of files not containing selected lines are written
to standard output. Pathnames are listed once per file searched.
If the standard input is searched, the string ``(standard input)''
is written. If --tree is specified, outputs directories in a
tree-like format.
-l, --files-with-matches
Only the names of files containing selected lines are written to
standard output. ugrep will only search a file until a match has
been found, making searches potentially less expensive. Pathnames
are listed once per file searched. If the standard input is
searched, the string ``(standard input)'' is written. If --tree
is specified, outputs directories in a tree-like format.
--label=LABEL
Displays the LABEL value when input is read from standard input
where a file name would normally be printed in the output.
Associates a filename extension with standard input when LABEL has
a suffix. The default value is `(standard input)'.
--line-buffered
Force output to be line buffered instead of block buffered.
--lines
Apply Boolean queries to match lines, the opposite of --files.
This is the default Boolean query mode to match specific lines.
-M MAGIC, --file-magic=MAGIC
Only files matching the signature pattern MAGIC are searched. The
signature "magic bytes" at the start of a file are compared to the
MAGIC regex pattern. When matching, the file will be searched.
When MAGIC is preceded by a `!' or a `^', skip files with matching
MAGIC signatures. This option may be repeated and may be combined
with options -O and -t to expand the search. Every file on the
search path is read, making searches potentially more expensive.
-m [MIN,][MAX], --min-count=MIN, --max-count=MAX
Require MIN matches, stop after MAX matches when specified.
Output MIN to MAX matches. For example, -m1 outputs the first
match and -cm1, (with a comma) counts non-zero matches. See also
option -K.
--match
Match all input. Same as specifying an empty pattern to search.
--max-files=NUM
Restrict the number of files matched to NUM. Note that --sort or
-J1 may be specified to produce replicable results. If --sort is
specified, the number of threads spawned is limited to NUM.
--mmap[=MAX]
Use memory maps to search files. By default, memory maps are used
under certain conditions to improve performance. When MAX is
specified, use up to MAX mmap memory per thread.
-N PATTERN, --neg-regexp=PATTERN
Specify a negative PATTERN used during the search of the input: an
input line is selected only if it matches the specified patterns
unless it matches the negative PATTERN. Same as -e (?^PATTERN).
Negative pattern matches are essentially removed before any other
patterns are matched. Note that longer patterns take precedence
over shorter patterns. This option may be repeated.
-n, --line-number
Each output line is preceded by its relative line number in the
file, starting at line 1. The line number counter is reset for
each file processed.
--no-group-separator
Removes the group separator line from the output for context
options -A, -B and -C.
--not [-e] PATTERN
Specifies that PATTERN should not match. Note that -e A --not -e
B matches lines with `A' or lines without a `B'. To match lines
with `A' that have no `B', specify -e A --andnot -e B. Option
--stats displays the search patterns applied. See also options
--and, --andnot, --bool, --files and --lines.
-O EXTENSIONS, --file-extension=EXTENSIONS
Search only files whose filename extensions match the specified
comma-separated list of EXTENSIONS, same as --include='*.ext' for
each `ext' in EXTENSIONS. When an `ext' is preceded by a `!' or a
`^', skip files whose filename extensions matches `ext', same as
--exclude='*.ext'. This option may be repeated and may be
combined with options -g, -M and -t to expand the recursive
search.
-o, --only-matching
Output only the matching part of lines. Output additional matches
on the same line with `+' as the field separator. When multiple
lines match a pattern, output the matching lines with `|' as the
field separator. If -A, -B or -C is specified, fits the match and
its context on a line within the specified number of columns.
--only-line-number
The line number of the matching line in the file is output without
displaying the match. The line number counter is reset for each
file processed.
--files
Apply Boolean queries to match files, the opposite of --lines. A
file matches if all Boolean conditions are satisfied by the lines
matched in the file. For example, --files -e A --and -e B -e C
--andnot -e D matches a file if some lines match `A' and some
lines match (`B' or `C') and no line in the file matches `D'. May
also be specified as --files --bool 'A B|C -D'. Option -v cannot
be specified with --files. See also options --and, --andnot,
--not, --bool and --lines.
-P, --perl-regexp
Interpret PATTERN as a Perl regular expression using PCRE2. Note
that Perl pattern matching differs from the default grep POSIX
pattern matching.
-p, --no-dereference
If -R or -r is specified, no symbolic links are followed, even
when they are specified on the command line.
--pager[=COMMAND]
When output is sent to the terminal, uses COMMAND to page through
the output. The default COMMAND is `less -R'. Enables --heading
and --line-buffered.
--pretty
When output is sent to a terminal, enables --color, --heading, -n,
--sort, --tree and -T when not explicitly disabled.
-Q[DELAY], --query[=DELAY]
Query mode: user interface to perform interactive searches. This
mode requires an ANSI capable terminal. An optional DELAY
argument may be specified to reduce or increase the response time
to execute searches after the last key press, in increments of
100ms, where the default is 5 (0.5s delay). No whitespace may be
given between -Q and its argument DELAY. Initial patterns may be
specified with -e PATTERN, i.e. a PATTERN argument requires option
-e. Press F1 or CTRL-Z to view the help screen. Press F2 or
CTRL-Y to invoke a command to view or edit the file shown at the
top of the screen. The command can be specified with option
--view, or defaults to environment variable PAGER if defined, or
EDITOR. Press Tab and Shift-Tab to navigate directories and to
select a file to search. Press Enter to select lines to output.
Press ALT-l for option -l to list files, ALT-n for -n, etc.
Non-option commands include ALT-] to increase fuzziness and ALT-}
to increase context. Enables --heading. See also options
--confirm and --view.
-q, --quiet, --silent
Quiet mode: suppress all output. ugrep will only search until a
match has been found.
-R, --dereference-recursive
Recursively read all files under each directory. Follow all
symbolic links, unlike -r. See also option --sort.
-r, --recursive
Recursively read all files under each directory, following
symbolic links only if they are specified on the command line.
Note that when no FILE arguments are specified and input is read
from a terminal, recursive searches are performed as if -r is
specified. See also option --sort.
--replace=FORMAT
Replace matching patterns in the output by the specified FORMAT
with `%' fields. If -P is specified, FORMAT may include `%1' to
`%9', `%[NUM]#' and `%[NAME]#' to output group captures. A `%%'
outputs `%' and `%~' outputs a newline. See option --format,
`ugrep --help format' and `man ugrep' section FORMAT for details.
-S, --dereference
If -r is specified, all symbolic links are followed, like -R. The
default is not to follow symbolic links to directories.
-s, --no-messages
Silent mode: nonexistent and unreadable files are ignored, i.e.
their error messages and warnings are suppressed.
--save-config[=FILE]
Save configuration FILE. By default `.ugrep' is saved. If FILE
is a `-', write the configuration to standard output.
--separator[=SEP]
Use SEP as field separator between file name, line number, column
number, byte offset and the matched line. The default is a colon
(`:'), a plus (`+') for additional matches on the same line, and a
bar (`|') for multi-line pattern matches.
--sort[=KEY]
Displays matching files in the order specified by KEY in recursive
searches. Normally the ug command sorts by name whereas the ugrep
batch command displays matches in no particular order to improve
performance. The sort KEY can be `name' to sort by pathname
(default), `best' to sort by best match with option -Z (sort by
best match requires two passes over files, which is expensive),
`size' to sort by file size, `used' to sort by last access time,
`changed' to sort by last modification time and `created' to sort
by creation time. Sorting is reversed with `rname', `rbest',
`rsize', `rused', `rchanged', or `rcreated'. Archive contents are
not sorted. Subdirectories are sorted and displayed after
matching files. FILE arguments are searched in the same order as
specified.
--stats
Output statistics on the number of files and directories searched
and the inclusion and exclusion constraints applied.
-T, --initial-tab
Add a tab space to separate the file name, line number, column
number and byte offset with the matched line.
-t TYPES, --file-type=TYPES
Search only files associated with TYPES, a comma-separated list of
file types. Each file type corresponds to a set of filename
extensions passed to option -O and filenames passed to option -g.
For capitalized file types, the search is expanded to include
files with matching file signature magic bytes, as if passed to
option -M. When a type is preceded by a `!' or a `^', excludes
files of the specified type. This option may be repeated. The
possible file types can be (where -tlist displays a detailed
list): `actionscript', `ada', `asm', `asp', `aspx', `autoconf',
`automake', `awk', `Awk', `basic', `batch', `bison', `c', `c++',
`clojure', `cpp', `csharp', `css', `csv', `dart', `Dart',
`delphi', `elisp', `elixir', `erlang', `fortran', `gif', `Gif',
`go', `groovy', `gsp', `haskell', `html', `jade', `java', `jpeg',
`Jpeg', `js', `json', `jsp', `julia', `kotlin', `less', `lex',
`lisp', `lua', `m4', `make', `markdown', `matlab', `node', `Node',
`objc', `objc++', `ocaml', `parrot', `pascal', `pdf', `Pdf',
`perl', `Perl', `php', `Php', `png', `Png', `prolog', `python',
`Python', `r', `rpm', `Rpm', `rst', `rtf', `Rtf', `ruby', `Ruby',
`rust', `scala', `scheme', `shell', `Shell', `smalltalk', `sql',
`svg', `swift', `tcl', `tex', `text', `tiff', `Tiff', `tt',
`typescript', `verilog', `vhdl', `vim', `xml', `Xml', `yacc',
`yaml'.
--tabs[=NUM]
Set the tab size to NUM to expand tabs for option -k. The value
of NUM may be 1, 2, 4, or 8. The default tab size is 8.
--tag[=TAG[,END]]
Disables colors to mark up matches with TAG. END marks the end of
a match if specified, otherwise TAG. The default is `___'.
--tree, -^
Output directories with matching files in a tree-like format when
options -c, -l or -L are used. This option is enabled by --pretty
when the output is sent to a terminal.
-U, --binary
Disables Unicode matching for binary file matching, forcing
PATTERN to match bytes, not Unicode characters. For example, -U
'\xa3' matches byte A3 (hex) instead of the Unicode code point
U+00A3 represented by the UTF-8 sequence C2 A3. See also option
--dotall.
-u, --ungroup
Do not group multiple pattern matches on the same matched line.
Output the matched line again for each additional pattern match,
using `+' as a separator.
-V, --version
Display version with linked libraries and exit.
-v, --invert-match
Selected lines are those not matching any of the specified
patterns.
--view[=COMMAND]
Use COMMAND to view/edit a file in query mode when pressing
CTRL-Y.
-W, --with-hex
Output binary matches in hexadecimal, leaving text matches alone.
This option is equivalent to the --binary-files=with-hex option
with --hexdump=2C. To omit the matching line from the hex output,
combine option --hexdump with option -W. See also option -U.
-w, --word-regexp
The PATTERN is searched for as a word, such that the matching text
is preceded by a non-word character and is followed by a non-word
character. Word characters are letters, digits and the
underscore. With option -P, word characters are Unicode letters,
digits and underscore. This option has no effect if -x is also
specified. If a PATTERN is specified, or -e PATTERN or -N
PATTERN, then this option has no effect on -f FILE patterns to
allow -f FILE patterns to narrow or widen the scope of the PATTERN
search.
--width[=NUM]
Truncate the output to NUM visible characters per line. The width
of the terminal window is used if NUM is not specified. Note that
double wide characters in the output may result in wider lines.
-X, --hex
Output matches in hexadecimal. This option is equivalent to the
--binary-files=hex option with --hexdump=2C. To omit the matching
line from the hex output, use option --hexdump instead of -X. See
also option -U.
-x, --line-regexp
Select only those matches that exactly match the whole line, as if
the patterns are surrounded by ^ and $. If a PATTERN is
specified, or -e PATTERN or -N PATTERN, then this option has no
effect on -f FILE patterns to allow -f FILE patterns to narrow or
widen the scope of the PATTERN search.
--xml Output file matches in XML. If -H, -n, -k, or -b is specified,
additional values are output. See also options --format and -u.
-Y, --empty
Permits empty matches. By default, empty matches are disabled,
unless a pattern begins with `^' or ends with `$'. With this
option, empty-matching patterns such as x? and x*, match all
input, not only lines containing the character `x'.
-y, --any-line, --passthru
Any line is output (passthru). Non-matching lines are output as
context with a `-' separator. See also options -A, -B and -C.
-Z[best][+-~][MAX], --fuzzy=[best][+-~][MAX]
Fuzzy mode: report approximate pattern matches within MAX errors.
The default is -Z1: one deletion, insertion or substitution is
allowed. If `+`, `-' and/or `~' is specified, then `+' allows
insertions, `-' allows deletions and `~' allows substitutions.
For example, -Z+~3 allows up to three insertions or substitutions,
but no deletions. If `best' is specified, then only the best
matching lines are output with the lowest cost per file. Option
-Zbest requires two passes over a file and cannot be used with
standard input or Boolean queries. Option --sort=best orders
matching files by best match. The first character of an
approximate match always matches a character at the beginning of
the pattern. To fuzzy match the first character, replace it with
a `.' or `.?'. Option -U applies fuzzy matching to ASCII and
bytes instead of Unicode text. No whitespace may be given between
-Z and its argument.
-z, --decompress
Decompress files to search, when compressed. Archives (.cpio,
.pax, .tar and .zip) and compressed archives (e.g. .taz, .tgz,
.tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, .txz, .tzst) are searched and
matching pathnames of files in archives are output in braces. If
-g, -O, -M, or -t is specified, searches files stored in archives
whose filenames match globs, match filename extensions, match file
signature magic bytes, or match file types, respectively.
Supported compression formats: gzip (.gz), compress (.Z), zip,
bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2,
.tz2), lzma and xz (requires suffix .lzma, .tlz, .xz, .txz), lz4
(requires suffix .lz4), zstd (requires suffix .zst, .zstd, .tzst).
--zmax=NUM
When used with option -z (--decompress), searches the contents of
compressed files and archives stored within archives by up to NUM
recursive expansions. The default --zmax=1 only permits searching
uncompressed files stored in cpio, pax, tar and zip archives;
compressed files and archives are detected as binary files and are
effectively ignored. Specify --zmax=2 to search compressed files
and archives stored in cpio, pax, tar and zip archives. NUM may
range from 1 to 99 for up to 99 decompression and de-archiving
steps. Increasing NUM values gradually degrades performance.
-0, --null
Output a zero-byte (NUL) after the file name. This option can be
used with commands such as `find -print0' and `xargs -0' to
process arbitrary file names.
A `--' signals the end of options; the rest of the parameters are FILE
arguments, allowing filenames to begin with a `-' character.
Long options may start with `--no-' to disable, when applicable.
The regular expression pattern syntax is an extended form of the POSIX
ERE syntax. For an overview of the syntax see README.md or visit:
https://github.com/Genivia/ugrep
Note that `.' matches any non-newline character. Pattern `\n' matches a
newline character. Multiple lines may be matched with patterns that
match one or more newline characters.
EXIT STATUS
The ugrep utility exits with one of the following values:
0 One or more lines were selected.
1 No lines were selected.
>1 An error occurred.
If -q or --quiet or --silent is used and a line is selected, the exit
status is 0 even if an error occurred.
CONFIGURATION
The ug command is intended for context-dependent interactive searching
and is equivalent to the ugrep --config command to load the default
configuration file `.ugrep' when present in the working directory or in
the home directory.
A configuration file contains `NAME=VALUE' pairs per line, where `NAME`
is the name of a long option (without `--') and `=VALUE' is an argument,
which is optional and may be omitted depending on the option. Empty
lines and lines starting with a `#' are ignored.
The --config=FILE option and its abbreviated form ---FILE load the
specified configuration file located in the working directory or, when
not found, located in the home directory. An error is produced when FILE
is not found or cannot be read.
Command line options are parsed in the following order: the configuration
file is loaded first, followed by the remaining options and arguments on
the command line.
The --save-config option saves a `.ugrep' configuration file to the
working directory with a subset of the current options. The --save-
config=FILE option saves the configuration to FILE. The configuration is
written to standard output when FILE is a `-'.
GLOBBING
Globbing is used by options -g, --include, --include-dir, --include-from,
--exclude, --exclude-dir, --exclude-from and --ignore-files to match
pathnames and basenames in recursive searches. Glob arguments for these
options should be quoted to prevent shell globbing.
Globbing supports gitignore syntax and the corresponding matching rules,
except that a glob normally matches files but not directories. If a glob
ends in a path separator `/', then it matches directories but not files,
as if --include-dir or --exclude-dir is specified. When a glob contains
a path separator `/', the full pathname is matched. Otherwise the
basename of a file or directory is matched. For example, *.h matches
foo.h and bar/foo.h. bar/*.h matches bar/foo.h but not foo.h and not
bar/bar/foo.h. Use a leading `/' to force /*.h to match foo.h but not
bar/foo.h.
When a glob starts with a `^' or a `!' as in -g^GLOB, the match is
negated. Likewise, a `!' (but not a `^') may be used with globs in the
files specified --include-from, --exclude-from, and --ignore-files to
negate the glob match. Empty lines or lines starting with a `#' are
ignored.
Glob Syntax and Conventions
* Matches anything except /.
? Matches any one character except /.
[abc-e]
Matches one character a,b,c,d,e.
[^abc-e]
Matches one character not a,b,c,d,e,/.
[!abc-e]
Matches one character not a,b,c,d,e,/.
/ When used at the start of a glob, matches if pathname has no /.
When used at the end of a glob, matches directories only.
**/ Matches zero or more directories.
/** When used at the end of a glob, matches everything after the /.
\? Matches a ? or any other character specified after the backslash.
Glob Matching Examples
* Matches a, b, x/a, x/y/b
a Matches a, x/a, x/y/a, but not b, x/b, a/a/b
/* Matches a, b, but not x/a, x/b, x/y/a
/a Matches a, but not x/a, x/y/a
a?b Matches axb, ayb, but not a, b, ab, a/b
a[xy]b Matches axb, ayb but not a, b, azb
a[a-z]b
Matches aab, abb, acb, azb, but not a, b, a3b, aAb, aZb
a[^xy]b
Matches aab, abb, acb, azb, but not a, b, axb, ayb
a[^a-z]b
Matches a3b, aAb, aZb but not a, b, aab, abb, acb, azb
a/*/b Matches a/x/b, a/y/b, but not a/b, a/x/y/b
**/a Matches a, x/a, x/y/a, but not b, x/b.
a/**/b Matches a/b, a/x/b, a/x/y/b, but not x/a/b, a/b/x
a/** Matches a/x, a/y, a/x/y, but not a, b/x
a\?b Matches a?b, but not a, b, ab, axb, a/b
Note that exclude glob patterns take priority over include glob patterns
when specified with options -g, --exclude, --exclude-dir, --include and
include-dir.
Glob patterns specified with prefix `!' in any of the files associated
with --include-from, --exclude-from and --ignore-files will negate a
previous glob match. That is, any matching file or directory excluded by
a previous glob pattern specified in the files associated with --exclude-
from or --ignore-file will become included again. Likewise, any matching
file or directory included by a previous glob pattern specified in the
files associated with --include-from will become excluded again.
ENVIRONMENT
GREP_PATH
May be used to specify a file path to pattern files. The file
path is used by option -f to open a pattern file, when the pattern
file does not exist.
GREP_COLOR
May be used to specify ANSI SGR parameters to highlight matches
when option --color is used, e.g. 1;35;40 shows pattern matches in
bold magenta text on a black background. Deprecated in favor of
GREP_COLORS, but still supported.
GREP_COLORS
May be used to specify ANSI SGR parameters to highlight matches
and other attributes when option --color is used. Its value is a
colon-separated list of ANSI SGR parameters that defaults to
cx=33:mt=1;31:fn=1;35:ln=1;32:cn=1;32:bn=1;32:se=36. The mt=,
ms=, and mc= capabilities of GREP_COLORS take priority over
GREP_COLOR. Option --colors takes priority over GREP_COLORS.
GREP_COLORS
Colors are specified as string of colon-separated ANSI SGR parameters of
the form `what=substring', where `substring' is a semicolon-separated
list of ANSI SGR codes or `k' (black), `r' (red), `g' (green), `y'
(yellow), `b' (blue), `m' (magenta), `c' (cyan), `w' (white). Upper case
specifies background colors. A `+' qualifies a color as bright. A
foreground and a background color may be combined with one or more font
properties `n' (normal), `f' (faint), `h' (highlight), `i' (invert), `u'
(underline). Substrings may be specified for:
sl= SGR substring for selected lines.
cx= SGR substring for context lines.
rv Swaps the sl= and cx= capabilities when -v is specified.
mt= SGR substring for matching text in any matching line.
ms= SGR substring for matching text in a selected line. The substring
mt= by default.
mc= SGR substring for matching text in a context line. The substring
mt= by default.
fn= SGR substring for filenames.
ln= SGR substring for line numbers.
cn= SGR substring for column numbers.
bn= SGR substring for byte offsets.
se= SGR substring for separators.
rv a Boolean parameter, switches sl= and cx= with option -v.
hl a Boolean parameter, enables filename hyperlinks (\33]8;;link).
ne a Boolean parameter, disables ``erase in line'' \33[K.
FORMAT
Option --format=FORMAT specifies an output format for file matches.
Fields may be used in FORMAT, which expand into the following values:
%[ARG]F
if option -H is used: ARG, the file pathname and separator.
%f the file pathname.
%a the file basename without directory path.
%p the directory path to the file.
%z the file pathname in a (compressed) archive.
%[ARG]H
if option -H is used: ARG, the quoted pathname and separator, \"
and \\ replace " and \.
%h the quoted file pathname, \" and \\ replace " and \.
%[ARG]N
if option -n is used: ARG, the line number and separator.
%n the line number of the match.
%[ARG]K
if option -k is used: ARG, the column number and separator.
%k the column number of the match.
%[ARG]B
if option -b is used: ARG, the byte offset and separator.
%b the byte offset of the match.
%[ARG]T
if option -T is used: ARG and a tab character.
%t a tab character.
%[SEP]$
set field separator to SEP for the rest of the format fields.
%[ARG]<
if the first match: ARG.
%[ARG]>
if not the first match: ARG.
%, if not the first match: a comma, same as %[,]>.
%: if not the first match: a colon, same as %[:]>.
%; if not the first match: a semicolon, same as %[;]>.
%| if not the first match: a vertical bar, same as %[|]>.
%[ARG]S
if not the first match: ARG and separator, see also %[SEP]$.
%s the separator, see also %[ARG]S and %[SEP]$.
%~ a newline character.
%M the number of matching lines
%m the number of matches
%O the matching line is output as a raw string of bytes.
%o the match is output as a raw string of bytes.
%Q the matching line as a quoted string, \" and \\ replace " and \.
%q the match as a quoted string, \" and \\ replace " and \.
%C the matching line formatted as a quoted C/C++ string.
%c the match formatted as a quoted C/C++ string.
%J the matching line formatted as a quoted JSON string.
%j the match formatted as a quoted JSON string.
%V the matching line formatted as a quoted CSV string.
%v the match formatted as a quoted CSV string.
%X the matching line formatted as XML character data.
%x the match formatted as XML character data.
%w the width of the match, counting wide characters.
%d the size of the match, counting bytes.
%e the ending byte offset of the match.
%Z the edit distance cost of an approximate match with option -Z
%u select unique lines only, unless option -u is used.
%1 the first regex group capture of the match, and so on up to group
%9, same as %[1]#; requires option -P.
%[NUM]#
the regex group capture NUM; requires option -P.
%[NUM]b
the byte offset of the group capture NUM; requires option -P. Use
e for the ending byte offset and d for the byte length.
%[NUM1|NUM2|...]#
the first group capture NUM that matched; requires option -P.
%[NUM1|NUM2|...]b
the byte offset of the first group capture NUM that matched;
requires option -P. Use e for the ending byte offset and d for
the byte length.
%[NAME]#
the NAMEd group capture; requires option -P and capturing pattern
`(?<NAME>PATTERN)', see also %G.
%[NAME]b
the byte offset of the NAMEd group capture; requires option -P and
capturing pattern `(?<NAME>PATTERN)'. Use e for the ending byte
offset and d for the byte length.
%[NAME1|NAME2|...]#
the first NAMEd group capture that matched; requires option -P and
capturing pattern `(?<NAME>PATTERN)', see also %G.
%[NAME1|NAME2|...]b
the byte offset of the first NAMEd group capture that matched;
requires option -P and capturing pattern `(?<NAME>PATTERN)'. Use
e for the ending byte offset and d for the byte length.
%G list of group capture indices/names that matched; requires option
-P.
%[TEXT1|TEXT2|...]G
list of TEXT indexed by group capture indices that matched;
requires option -P.
%g the group capture index/name matched or 1; requires option -P.
%[TEXT1|TEXT2|...]g
the first TEXT indexed by the first group capture index that
matched; requires option -P.
%% the percentage sign.
Formatted output is written without a terminating newline, unless %~ or
`\n' is explicitly specified in the format string.
The [ARG] part of a field is optional and may be omitted. When present,
the argument must be placed in [] brackets, for example %[,]F to output a
comma, the pathname, and a separator.
%[SEP]$ and %u are switches and do not send anything to the output.
The separator used by the %F, %H, %N, %K, %B, %S and %G fields may be
changed by preceding the field by %[SEP]$. When [SEP] is not provided,
this reverts the separator to the default separator or the separator
specified with --separator.
Formatted output is written for each matching pattern, which means that a
line may be output multiple times when patterns match more than once on
the same line. If field %u is specified anywhere in a format string,
matching lines are output only once, unless option -u, --ungroup is
specified or when more than one line of input matched the search pattern.
Additional formatting options:
--format-begin=FORMAT
the FORMAT when beginning the search.
--format-open=FORMAT
the FORMAT when opening a file and a match was found.
--format-close=FORMAT
the FORMAT when closing a file and a match was found.
--format-end=FORMAT
the FORMAT when ending the search.
The context options -A, -B, -C, -y, and display options --break,
--heading, --color, -T, and --null have no effect on formatted output.
EXAMPLES
Display lines containing the word `patricia' in `myfile.txt':
$ ugrep -w patricia myfile.txt
Display lines containing the word `patricia', ignoring case:
$ ugrep -wi patricia myfile.txt
Display lines approximately matching the word `patricia', ignoring case
and allowing up to 2 spelling errors using fuzzy search:
$ ugrep -Z2 -wi patricia myfile.txt
Count the number of lines containing `patricia', ignoring case:
$ ugrep -cwi patricia myfile.txt
Count the number of words `patricia', ignoring case:
$ ugrep -cowi patricia myfile.txt
List lines with `amount' and a decimal, ignoring case (space is AND):
$ ugrep -i --bool 'amount +(.+)?' myfile.txt
Alternative query:
$ ugrep -wi -e amount --and '+(.+)?' myfile.txt
List all Unicode words in a file:
$ ugrep -o '\w+' myfile.txt
List all ASCII words in a file:
$ ugrep -o '[[:word:]]+' myfile.txt
List the laughing face emojis (Unicode code points U+1F600 to U+1F60F):
$ ugrep -o '[\x{1F600}-\x{1F60F}]' myfile.txt
Check if a file contains any non-ASCII (i.e. Unicode) characters:
$ ugrep -q '[^[:ascii:]]' myfile.txt && echo "contains Unicode"
Display the line and column number of `FIXME' in C++ files using
recursive search, with one line of context before and after a matched
line:
$ ugrep -C1 -R -n -k -tc++ FIXME
Display the line and column number of `FIXME' in long Javascript files
using recursive search, showing only matches with up to 10 characters of
context before and after:
$ ugrep -o -C20 -R -n -k -tjs FIXME
List the C/C++ comments in a file with line numbers:
$ ugrep -n -e '//.*' -e '/\*([^*]|(\*+[^*/]))*\*+\/' myfile.cpp
The same, but using predefined pattern c++/comments:
$ ugrep -n -f c++/comments myfile.cpp
List the lines that need fixing in a C/C++ source file by looking for the
word `FIXME' while skipping any `FIXME' in quoted strings:
$ ugrep -e FIXME -N '"(\\.|\\\r?\n|[^\\\n"])*"' myfile.cpp
The same, but using predefined pattern cpp/zap_strings:
$ ugrep -e FIXME -f cpp/zap_strings myfile.cpp
Find lines with `FIXME' or `TODO', showing line numberes:
$ ugrep -n -e FIXME -e TODO myfile.cpp
Find lines with `FIXME' that also contain `urgent':
$ ugrep -n -e FIXME --and urgent myfile.cpp
The same, but with a Boolean query pattern (a space is AND):
$ ugrep -n --bool 'FIXME urgent' myfile.cpp
Find lines with `FIXME' that do not also contain `later':
$ ugrep -n -e FIXME --andnot later myfile.cpp
The same, but with a Boolean query pattern (a space is AND, - is NOT):
$ ugrep -n --bool 'FIXME -later' myfile.cpp
Output a list of line numbers of lines with `FIXME' but not `later':
$ ugrep -e FIXME --andnot later --format='%,%n' myfile.cpp
Recursively list all files with both `FIXME' and `LICENSE' anywhere in
the file, not necessarily on the same line:
$ ugrep -l --files --bool 'FIXME LICENSE'
Find lines with `FIXME' in the C/C++ files stored in a tarball:
$ ugrep -z -tc++ -n FIXME project.tgz
Recursively find lines with `FIXME' in C/C++ files, but do not search any
`bak' and `old' directories:
$ ugrep -n FIXME -tc++ -g^bak/,^old/
Recursively search for the word `copyright' in cpio/jar/pax/tar/zip
archives, compressed and regular files, and in PDFs using a PDF filter:
$ ugrep -z -w --filter='pdf:pdftotext % -' copyright
Match the binary pattern `A3hhhhA3' (hex) in a binary file without
Unicode pattern matching -U (which would otherwise match `\xaf' as a
Unicode character U+00A3 with UTF-8 byte sequence C2 A3) and display the
results in hex with --hexdump with C1 to output one hex line before and
after each match:
$ ugrep -U --hexdump=C1 '\xa3[\x00-\xff]{2}\xa3' a.out
Hexdump an entire file using a pager for viewing:
$ ugrep -X --pager '' a.out
List all files that are not ignored by one or more `.gitignore':
$ ugrep -l '' --ignore-files
List all files containing a RPM signature, located in the `rpm' directory
and recursively below up to two levels deeper (3 levels total):
$ ugrep -3 -l -tRpm '' rpm/
Monitor the system log for bug reports and ungroup multiple matches on a
line:
$ tail -f /var/log/system.log | ugrep -u -i -w bug
Interactive fuzzy search with Boolean search queries:
$ ugrep -Q --bool -Z3 --sort=best
Display all words in a MacRoman-encoded file that has CR newlines:
$ ugrep --encoding=MACROMAN '\w+' mac.txt
Display options related to "fuzzy" searching:
$ ugrep --help fuzzy
BUGS
Report bugs at:
https://github.com/Genivia/ugrep/issues
LICENSE
ugrep is released under the BSD-3 license. All parts of the software
have reasonable copyright terms permitting free redistribution. This
includes the ability to reuse all or parts of the ugrep source tree.
SEE ALSO
grep(1).
ugrep 3.11.2 April 7, 2023 UGREP(1)
🔝 [Back to table of contents](#toc)
<a name="patterns"/>
Regex patterns
--------------
For PCRE regex patterns with option `-P`, please see the PCRE documentation
<https://www.pcre.org/original/doc/html/pcrepattern.html>. The pattern syntax
has more features than the pattern syntax described below. For the patterns in
common the syntax and meaning are the same.
Note that `\s` and inverted bracket lists `[^...]` are modified in **ugrep** to
prevent matching newlines `\n`. This modification is done to replicate the
behavior of grep.
<a name="posix-syntax"/>
### POSIX regular expression syntax
An empty pattern is a special case that matches everything except empty files,
i.e. does not match zero-length files, as per POSIX.1 grep standard.
A regex pattern is an extended set of regular expressions (ERE), with nested
sub-expression patterns `φ` and `ψ`:
Pattern | Matches
--------- | -----------------------------------------------------------------
`x` | matches the character `x`, where `x` is not a special character
`.` | matches any single character except newline (unless in dotall mode)
`\.` | matches `.` (dot), special characters are escaped with a backslash
`\n` | matches a newline, others are `\a` (BEL), `\b` (BS), `\t` (HT), `\v` (VT), `\f` (FF), and `\r` (CR)
`\0` | matches the NUL character
`\cX` | matches the control character `X` mod 32 (e.g. `\cA` is `\x01`)
`\0141` | matches an 8-bit character with octal value `141`, i.e. `a`
`\x7f` | matches an 8-bit character with hexadecimal value `7f`
`\x{3B1}` | matches Unicode character U+03B1, i.e. `α`
`\u{3B1}` | matches Unicode character U+03B1, i.e. `α`
`\o{141}` | matches Unicode character U+0061, i.e. `a`, in octal
`\p{C}` | matches a character in Unicode category C
`\Q...\E` | matches the quoted content between `\Q` and `\E` literally
`[abc]` | matches one of `a`, `b`, or `c`
`[0-9]` | matches a digit `0` to `9`
`[^0-9]` | matches any character except a digit and excluding newline `\n`
`φ?` | matches `φ` zero or one time (optional)
`φ*` | matches `φ` zero or more times (repetition)
`φ+` | matches `φ` one or more times (repetition)
`φ{2,5}` | matches `φ` two to five times (repetition)
`φ{2,}` | matches `φ` at least two times (repetition)
`φ{2}` | matches `φ` exactly two times (repetition)
`φ??` | matches `φ` zero or once as needed (lazy optional)
`φ*?` | matches `φ` a minimum number of times as needed (lazy repetition)
`φ+?` | matches `φ` a minimum number of times at least once as needed (lazy repetition)
`φ{2,5}?` | matches `φ` two to five times as needed (lazy repetition)
`φ{2,}?` | matches `φ` at least two times or more as needed (lazy repetition)
`φψ` | matches `φ` then matches `ψ` (concatenation)
`φ⎮ψ` | matches `φ` or matches `ψ` (alternation)
`(φ)` | matches `φ` as a group
`(?:φ)` | matches `φ` as a group without capture
`(?=φ)` | matches `φ` without consuming it, i.e. lookahead (without option `-P`: nothing may occur after `(?=φ)`)
`(?^φ)` | matches `φ` and ignores it, marking everything in the pattern as a non-match
`^φ` | matches `φ` at the start of input or start of a line (nothing may occur before `^`)
`φ$` | matches `φ` at the end of input or end of a line (nothing may occur after `$`)
`\Aφ` | matches `φ` at the start of input (nothing may occur before `\A`)
`φ\z` | matches `φ` at the end of input (nothing may occur after `\z`)
`\bφ` | matches `φ` starting at a word boundary (without option `-P`: nothing may occur before `\b`)
`φ\b` | matches `φ` ending at a word boundary (without option `-P`: nothing may occur after `\b`)
`\Bφ` | matches `φ` starting at a non-word boundary (without option `-P`: nothing may occur before `\B`)
`φ\B` | matches `φ` ending at a non-word boundary (without option `-P`: nothing may occur after `\B`)
`\<φ` | matches `φ` that starts a word (without option `-P`: nothing may occur before `\<`)
`\>φ` | matches `φ` that starts a non-word (without option `-P`: nothing may occur before `\>`)
`φ\<` | matches `φ` that ends a non-word (without option `-P`: nothing may occur after `\<`)
`φ\>` | matches `φ` that ends a word (without option `-P`: nothing may occur after `\>`)
`(?i:φ)` | matches `φ` ignoring case
`(?s:φ)` | `.` (dot) in `φ` matches newline
`(?x:φ)` | ignore all whitespace and comments in `φ`
`(?#:X)` | all of `X` is skipped as a comment
The order of precedence for composing larger patterns from sub-patterns is as
follows, from high to low precedence:
1. Characters, character classes (bracket expressions), escapes, quotation
2. Grouping `(φ)`, `(?:φ)`, `(?=φ)`, and inline modifiers `(?imsux:φ)`
3. Quantifiers `?`, `*`, `+`, `{n,m}`
4. Concatenation `φψ`
5. Anchoring `^`, `$`, `\<`, `\>`, `\b`, `\B`, `\A`, `\z`
6. Alternation `φ|ψ`
7. Global modifiers `(?imsux)φ`
🔝 [Back to table of contents](#toc)
<a name="posix-classes"/>
### POSIX and Unicode character classes
Character classes in bracket lists represent sets of characters. Sets can be
negated (inverted), subtracted, intersected, and merged (not supported by PCRE2
with option `-P`):
Pattern | Matches
----------------- | ---------------------------------------------------------
`[a-zA-Z]` | matches a letter
`[^a-zA-Z]` | matches a non-letter (character class negation), newlines are not matched
`[a-z−−[aeiou]]` | matches a consonant (character class subtraction)
`[a-z&&[^aeiou]]` | matches a consonant (character class intersection)
`[a-z⎮⎮[A-Z]]` | matches a letter (character class union)
Bracket lists cannot be empty, so `[]` and `[^]` are invalid. In fact, the
first character after the bracket is always part of the list. So `[][]` is a
list that matches a `]` and a `[`, `[^][]` is a list that matches anything but
`]` and `[`, and `[-^]` is a list that matches a `-` and a `^`.
Negated character classes such as `[^a-z]` do not match newlines for
compatibility with traditional grep pattern matching.
🔝 [Back to table of contents](#toc)
<a name="posix-categories"/>
### POSIX and Unicode character categories
The POSIX form can only be used in bracket lists, for example
`[[:lower:][:digit:]]` matches an ASCII lower case letter or a digit.
You can also use the `\p{C}` form for class `C` and upper case `\P{C}` form
that has the same meaning as `\p{^C}`, which matches any character except
characters in the class `C`. For example, `\P{ASCII}` is the same as
`\p{^ASCII}` which is the same as `[[:^ascii]]`.
POSIX form | POSIX category | Matches
------------ | ----------------- | ---------------------------------------------
`[:ascii:]` | `\p{ASCII}` | matches an ASCII character U+0000 to U+007F
`[:space:]` | | matches a white space character `[ \t\n\v\f\r]` or `\p{Space}` with `-P`
`[:xdigit:]` | `\p{Xdigit}` | matches a hex digit `[0-9A-Fa-f]`
`[:cntrl:]` | `\p{Cntrl}` | matches a control character `[\x00-\0x1f\x7f]`
`[:print:]` | `\p{Print}` | matches a printable character `[\x20-\x7e]`
`[:alnum:]` | `\p{Alnum}` | matches a alphanumeric character `[0-9A-Za-z]` or `[\p{L}\p{N}]` with `-P`
`[:alpha:]` | `\p{Alpha}` | matches a letter `[A-Za-z]` or `\p{L}` with `-P`
`[:blank:]` | `\p{Blank}`, `\h` | matches a blank `[ \t]` or horizontal space with `-P`
`[:digit:]` | `\p{Digit}` | matches a digit `[0-9]` or `\p{Nd}` with `-P`
`[:graph:]` | `\p{Graph}` | matches a visible character `[\x21-\x7e]`
`[:lower:]` | | matches a lower case letter `[a-z]` or `\p{Ll}` with `-P`
`[:punct:]` | `\p{Punct}` | matches a punctuation character `[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]`
`[:upper:]` | | matches an upper case letter `[A-Z]` or `\p{Lu}` with `-P`
`[:word:]` | | matches a word character `[0-9A-Za-z_]` or `[\p{L}\p{N}_]` with `-P`
`[:^blank:]` | `\P{Blank}`, `\H` | matches a non-blank character including newline `\n`
`[:^digit:]` | `\P{Digit}` | matches a non-digit including newline `\n`
POSIX character categories only cover ASCII, `[[:^ascii]]` is empty and
therefore invalid to use. By contrast, `[^[:ascii]]` is a Unicode character
class that excludes the ASCII character category.
Note that the patterns `[[:ascii:]]`, `[[:ctnrl:]]` and `[[:space:]]` and most
of the negated classes such as `[[:^blank:]]` and `[[:digit:]]` match newlines,
which is the official definition of these POSIX categories. By contrast,
GNU/BSD grep never match newlines. As a consequence, more patterns may match.
Negated character classes of the form `[^...]` match any Unicode character
except the given characters and does not match newlines either. For example
`[^[:digit:]]` matches non-digits (including Unicode) and does not match
newlines. By contrast, `[[:^digit:]]` matches ASCII non-digits, including
newlines.
Option `-U` disables Unicode wide-character matching, i.e. ASCII matching.
Unicode category | Matches
-------------------------------------- | ------------------------------------
`.` | matches any single Unicode character except newline `\n` unless with `--dotall`
`\a` | matches BEL U+0007
`\d` | matches a digit `[0-9]` or `\p{Nd}`
`\D` | matches a non-digit including `\n`
`\e` | matches ESC U+001b
`\f` | matches FF U+000c
`\l` | matches a lower case letter `\p{Ll}`
`\n` | matches LF U+000a
`\N` | matches a non-LF character
`\r` | matches CR U+000d
`\R` | matches a Unicode line break (`\r\n`, `\r`, `\v`, `\f`, `\n`, U+0085, U+2028 and U+2029)
`\s` | matches a white space character `[ \t\v\f\r\x85\p{Z}]` excluding `\n`
`\S` | matches a non-white space character
`\t` | matches TAB U+0009
`\u` | matches an upper case letter `\p{Lu}`
`\v` | matches VT U+000b or vertical space character with option `-P`
`\w` | matches a word character `[0-9A-Za-z_]` or `[\p{L}\p{Nd}\p{Pc}]`
`\W` | matches a non-Unicode word character
`\X` | matches any ISO-8859-1 or Unicode character
`\p{Space}` | matches a white space character `[ \t\n\v\f\r\x85\p{Z}]` including `\n`
`\p{Unicode}` | matches any Unicode character U+0000 to U+10FFFF minus U+D800 to U+DFFF
`\p{ASCII}` | matches an ASCII character U+0000 to U+007F
`\p{Non_ASCII_Unicode}` | matches a non-ASCII character U+0080 to U+10FFFF minus U+D800 to U+DFFF
`\p{L&}` | matches a character with Unicode property L& (i.e. property Ll, Lu, or Lt)
`\p{Letter}`,`\p{L}` | matches a character with Unicode property Letter
`\p{Mark}`,`\p{M}` | matches a character with Unicode property Mark
`\p{Separator}`,`\p{Z}` | matches a character with Unicode property Separator
`\p{Symbol}`,`\p{S}` | matches a character with Unicode property Symbol
`\p{Number}`,`\p{N}` | matches a character with Unicode property Number
`\p{Punctuation}`,`\p{P}` | matches a character with Unicode property Punctuation
`\p{Other}`,`\p{C}` | matches a character with Unicode property Other
`\p{Lowercase_Letter}`, `\p{Ll}` | matches a character with Unicode sub-property Ll
`\p{Uppercase_Letter}`, `\p{Lu}` | matches a character with Unicode sub-property Lu
`\p{Titlecase_Letter}`, `\p{Lt}` | matches a character with Unicode sub-property Lt
`\p{Modifier_Letter}`, `\p{Lm}` | matches a character with Unicode sub-property Lm
`\p{Other_Letter}`, `\p{Lo}` | matches a character with Unicode sub-property Lo
`\p{Non_Spacing_Mark}`, `\p{Mn}` | matches a character with Unicode sub-property Mn
`\p{Spacing_Combining_Mark}`, `\p{Mc}` | matches a character with Unicode sub-property Mc
`\p{Enclosing_Mark}`, `\p{Me}` | matches a character with Unicode sub-property Me
`\p{Space_Separator}`, `\p{Zs}` | matches a character with Unicode sub-property Zs
`\p{Line_Separator}`, `\p{Zl}` | matches a character with Unicode sub-property Zl
`\p{Paragraph_Separator}`, `\p{Zp}` | matches a character with Unicode sub-property Zp
`\p{Math_Symbol}`, `\p{Sm}` | matches a character with Unicode sub-property Sm
`\p{Currency_Symbol}`, `\p{Sc}` | matches a character with Unicode sub-property Sc
`\p{Modifier_Symbol}`, `\p{Sk}` | matches a character with Unicode sub-property Sk
`\p{Other_Symbol}`, `\p{So}` | matches a character with Unicode sub-property So
`\p{Decimal_Digit_Number}`, `\p{Nd}` | matches a character with Unicode sub-property Nd
`\p{Letter_Number}`, `\p{Nl}` | matches a character with Unicode sub-property Nl
`\p{Other_Number}`, `\p{No}` | matches a character with Unicode sub-property No
`\p{Dash_Punctuation}`, `\p{Pd}` | matches a character with Unicode sub-property Pd
`\p{Open_Punctuation}`, `\p{Ps}` | matches a character with Unicode sub-property Ps
`\p{Close_Punctuation}`, `\p{Pe}` | matches a character with Unicode sub-property Pe
`\p{Initial_Punctuation}`, `\p{Pi}` | matches a character with Unicode sub-property Pi
`\p{Final_Punctuation}`, `\p{Pf}` | matches a character with Unicode sub-property Pf
`\p{Connector_Punctuation}`, `\p{Pc}` | matches a character with Unicode sub-property Pc
`\p{Other_Punctuation}`, `\p{Po}` | matches a character with Unicode sub-property Po
`\p{Control}`, `\p{Cc}` | matches a character with Unicode sub-property Cc
`\p{Format}`, `\p{Cf}` | matches a character with Unicode sub-property Cf
`\p{UnicodeIdentifierStart}` | matches a character in the Unicode IdentifierStart class
`\p{UnicodeIdentifierPart}` | matches a character in the Unicode IdentifierPart class
`\p{IdentifierIgnorable}` | matches a character in the IdentifierIgnorable class
`\p{JavaIdentifierStart}` | matches a character in the Java IdentifierStart class
`\p{JavaIdentifierPart}` | matches a character in the Java IdentifierPart class
`\p{CsIdentifierStart}` | matches a character in the C# IdentifierStart class
`\p{CsIdentifierPart}` | matches a character in the C# IdentifierPart class
`\p{PythonIdentifierStart}` | matches a character in the Python IdentifierStart class
`\p{PythonIdentifierPart}` | matches a character in the Python IdentifierPart class
To specify a Unicode block as a category use `\p{IsBlockName}` with a Unicode
`BlockName`.
To specify a Unicode language script, use `\p{Language}` with a Unicode
`Language`.
Unicode language script character classes differ from the Unicode blocks that
have a similar name. For example, the `\p{Greek}` class represents Greek and
Coptic letters and differs from the Unicode block `\p{IsGreek}` that spans a
specific Unicode block of Greek and Coptic characters only, which also includes
unassigned characters.
🔝 [Back to table of contents](#toc)
<a name="perl-syntax"/>
### Perl regular expression syntax
For the pattern syntax of **ugrep** option `-P` (Perl regular expressions), see
for example [Perl regular expression syntax](https://www.boost.org/doc/libs/1_70_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html).
However, **ugrep** enhances the Perl regular expression syntax with all of the
features listed in [POSIX regular expression syntax](#posix-syntax).
🔝 [Back to table of contents](#toc)
<a name="bugs"/>
Troubleshooting
---------------
If something is not working, then please check the [tutorial](#tutorial) and
the [man page](#man). If you can't find it there and it looks like a bug, then
[report an issue](https://github.com/Genivia/ugrep/issues) on GitHub. Bug
reports are quickly addressed.
[ci-image]: https://github.com/Genivia/ugrep/actions/workflows/c-cpp.yml/badge.svg
[ci-url]: https://github.com/Genivia/ugrep/actions/workflows/c-cpp.yml
[bsd-3-image]: https://img.shields.io/badge/license-BSD%203--Clause-blue.svg
[bsd-3-url]: https://opensource.org/licenses/BSD-3-Clause
|