Linux readÏÂÁîµÄʹÓÃÒªÁì¼°¶ÁÈ¡ÎļþÄÚÈÝ
¡¾ÔõÑùʹÓÃLinux readÏÂÁî¶ÁÈ¡ÎļþÄÚÈÝ¡¿
ÔÚLinuxϵͳÖУ¬readÊÇÒ»¸öÓÃÓÚ´Ó±ê×¼ÊäÈë»òÕßÎļþÖжÁÈ¡Êý¾ÝµÄÏÂÁʹÓÃreadÏÂÁî¿ÉÒÔ×ÊÖúÓû§¿ìËÙ»ñÈ¡ÎļþÄÚÈÝ£¬²¢¾ÙÐкóÐøµÄ´¦Öóͷ£¡£ÏÂÃ潫ÏêϸÏÈÈÝÔõÑùʹÓÃLinux readÏÂÁî¶ÁÈ¡ÎļþÄÚÈÝ£¬°üÀ¨ÏêϸµÄ´úÂëʾÀý¡£
¶ÁÈ¡ÎļþÄÚÈÝ
Òª¶ÁÈ¡ÎļþÄÚÈÝ£¬Ê×ÏÈÐèÒª·¿ªÖնˣ¬²¢Ê¹ÓÃÒÔÏÂÏÂÁîÃûÌÃÀ´¶ÁÈ¡ÎļþÄÚÈÝ£º
read [-options] [variable]
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬-options´ú±íÖÖÖÖÑ¡Ïvariable´ú±í±äÁ¿Ãû³Æ£¬ÓÃÓÚ´æ´¢¶ÁÈ¡µÄÊý¾Ý¡£
´úÂëʾÀý
¼ÙÉèÎÒÃÇÓÐÒ»¸öÃûΪexample.txtµÄÎı¾Îļþ£¬ÄÚÈÝÈçÏ£º
Hello, this is an example file. Welcome to the world of Linux.
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ÏÖÔÚÎÒÃǽ«Ê¹ÓÃreadÏÂÁîÀ´¶ÁÈ¡Õâ¸öÎļþµÄÄÚÈÝ£¬²¢´æ´¢µ½±äÁ¿ÖС£ÔÚÖÕ¶ËÖÐÊäÈëÒÔÏÂÏÂÁ
while IFS= read -r line; do echo "$line" done < example.txt
µÇ¼ºó¸´ÖÆ
Ö´ÐÐÒÔÉÏÏÂÁîºó£¬Öն˻áÊä³öÎļþexample.txtµÄÄÚÈÝ£º
Hello, this is an example file. Welcome to the world of Linux.
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂëʾÀýÖУ¬whileÑ»·ÓÃÓÚÖðÐжÁÈ¡ÎļþÄÚÈÝ£¬IFS=ÓÃÓÚ±ÜÃâreadÏÂÁîÈ¥³ýÐÐÖеĿոñ£¬-rÑ¡ÏîÓÃÓÚ±£´æ·´Ð±¸Ü×Ö·ûµÄÔʼÐÎʽ¡£
¶ÁÈ¡Ö¸¶¨ÐÐ
ÓÐʱ¼äÎÒÃÇÖ»Ïë¶ÁÈ¡ÎļþÖеÄÌض¨ÐУ¬¿ÉÒÔʹÓÃÒÔÏÂÏÂÁ
read -r line_num < example.txt sed -n "${line_num}p" example.txt
µÇ¼ºó¸´ÖÆ
ÒÔÉÏ´úÂë»áÊ×ÏȶÁÈ¡ÎļþÖÐÖ¸¶¨ÐеÄÄÚÈÝ£¬È»ºóʹÓÃsedÏÂÁîÀ´Êä³ö¸ÃÐÐÄÚÈÝ¡£
ÆäËûÑ¡Ïî
³ýÁËʾÀýÖÐÌáµ½µÄ·½·¨Í⣬readÏÂÁîÉÐÓÐһЩÆäËû³£ÓõÄÑ¡ÏºÃ±È-tÓÃÓÚÉèÖó¬Ê±Ê±¼ä£¬-sÓÃÓÚ±£ÃÜÊäÈ룬-nÓÃÓÚÏÞÖƶÁÈëµÄ×Ö·ûÊýµÈ¡£
½áÓï
ͨ¹ýÒÔÉÏÒªÁ죬ÎÒÃÇ¿ÉÒÔÎÞаµØʹÓÃLinux readÏÂÁîÀ´¶ÁÈ¡ÎļþÄÚÈÝ£¬ÔÚ¾ÙÐÐÎı¾´¦Öóͷ£¡¢Êý¾ÝÆÊÎöµÈʹÃüʱºÜÊÇÓÐÓá£Ï£Íû±¾ÎÄÄÜ×ÊÖúÄú¸üºÃµØÏàʶºÍÓ¦ÓÃreadÏÂÁî¡£
ÒÔÉϾÍÊÇLinux readÏÂÁîµÄʹÓÃÒªÁì¼°¶ÁÈ¡ÎļþÄÚÈݵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡