簡體   English   中英

在Shell中讀取多行用戶輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM