I'd like to read input into variable and check if it contains TAB character. Here are two version of the code:
while read l && echo "$l" | grep -P '\t' ; do echo "$l $?"; done
while read && echo "$REPLY" | grep -P '\t' ; do echo "$REPLY $?"; done
Both versions work as desired if TAB is somewhere in the middle of the entered line.
Version with REPLY works as desired if TAB is at the end/beginning of the line.
Version with user variable doesn't work as desired if TAB is at the end/beginning of the line.
What do I miss? Why does it seem like version with REPLY can handle user input no matter the position of the TAB character and similar code with user variable works differently?
I'd like to read input into variable and check if it contains TAB
character. Here are two version of the code:
while read l && echo "$l" | grep -P '\t' ; do echo "$l $?"; done
while read && echo "$REPLY" | grep -P '\t' ; do echo "$REPLY $?"; done
Both versions work as desired if TAB is somewhere in the middle of the entered line.
Version with REPLY works as desired if TAB is at the end/beginning of
the line.
Version with user variable doesn't work as desired if TAB is at the end/beginning of the line.
What do I miss? Why does it seem like version with REPLY can handle user input no matter the position of the TAB character and similar code with
user variable works differently?
JaceK
On 2023-08-22 at 09:18 JaceK wrote:
I'd like to read input into variable and check if it contains TAB character. >> Here are two version of the code:
while read l && echo "$l" | grep -P '\t' ; do echo "$l $?"; done
while read && echo "$REPLY" | grep -P '\t' ; do echo "$REPLY $?"; done
Both versions work as desired if TAB is somewhere in the middle of the
entered line.
Version with REPLY works as desired if TAB is at the end/beginning of the line.
Version with user variable doesn't work as desired if TAB is at the
end/beginning of the line.
What do I miss? Why does it seem like version with REPLY can handle user
input no matter the position of the TAB character and similar code with user >> variable works differently?
Quoting bash man page where it describes the ‘read’ command: “The characters
in IFS are used to split the line into words using the same rules the shell uses for expansion […]”.
By default IFS contains SPACE, TAB and NEWLINE, so (multiple) SPACEs
and TABs are removed from the beginning and the end of the input line.
You need to eliminate TAB from IFS for your code to work as expected:
while IFS=$' \n' read l && echo "$l" | grep -P '\t' ; do echo "$l $?"; done
I guess REPLY contains the whole input line as entered, without any interpretation.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 498 |
Nodes: | 16 (2 / 14) |
Uptime: | 35:31:16 |
Calls: | 9,798 |
Files: | 13,751 |
Messages: | 6,189,275 |