![](/img/trans.png)
[英]Linux terminal input: reading user input from terminal truncating lines at 4095 character limit
[英]Reading multiple lines user input in Shell
嗨,我有一個程序,如果用戶輸入文件名,我將從文件中讀取文件,否則我將提示他們輸入。
目前我正在做:
input=$(cat)
echo $input>stdinput.txt
file=stdinput.txt
問題是它不能讀取輸入中的換行符,例如,如果我輸入
s,5,8
kyle,5,34,2
j,2
輸出
s,5,8 k,5,34,2 j,2
要存儲在文件中的預期輸出是
s,5,8
kyle,5,34,2
j,2
我需要知道閱讀時如何包括換行符。
echo
將取消換行符。 您不需要其他的$input
變量,因為您可以將cat
的輸出直接重定向到文件:
file=stdinput.txt
cat > "$file"
同樣,在cat
之前定義$file
對我來說更有意義。 改變了這一點。
如果在文件和$input
中都需要用戶輸入,那么tee
就足夠了。 如果將cat
(用戶輸入)的輸出通過管道傳遞到tee
則輸入將同時寫入文件和$input
:
file=stdinput.txt
input=$(cat | tee "$file")
嘗試在引用變量時引用它:
input=$(cat)
echo "$input">stdinput.txt
file=stdinput.txt
例:
$ input=$(cat)
s,5,8
kyle,5,34,2
j,2
$ echo "$input">stdinput.txt
$ cat stdinput.txt
s,5,8
kyle,5,34,2
j,2
$
實際上,不引用變量會導致您描述的情況
$ echo $input>stdinput.txt
$ cat stdinput.txt
s,5,8 kyle,5,34,2 j,2
$
您可以使用以下語法:
#!/bin/sh
cat > new_file << EOF
This will be line one
This will be line two
This will be line three
This will be line four indented
Notice the absence of spaces on the next line
EOF
在這里, cat
會讀取文本,直到遇到定界符(在本例中為EOF
)。 測力計字符串可以是任何東西。
printf
有所幫助嗎?
printf "$input">stdinput.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.